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

import com.bocloud.cmp.driver.f5.F5PartitionDriver;
import com.bocloud.cmp.model.f5.PartitionModel;
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.BiPartition;
import com.bocloud.ims.interfaces.resource.f5.F5BiPartitionService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.f5.F5BiPartitionRepository;
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("f5BiPartitionService")
public class F5BiPartitionServiceImpl implements F5BiPartitionService {
    private static final Logger logger = LoggerFactory.getLogger(F5BiPartitionServiceImpl.class);
    @Autowired
    private F5BiPartitionRepository f5BiPartitionRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private F5PartitionDriver f5PartitionDriver;

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

    @Override
    public BocloudResult create(BiPartition biPartition, Long userId) {
        String path = Kvs.class.getSimpleName() + "_" + biPartition.getId();
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            // 云平台id
            Long vendorId = biPartition.getVendorId();
            boolean isExists = f5BiPartitionRepository.existName(biPartition.getName(), vendorId);
            if (isExists) {
                return new BocloudResult(false, "添加失败：该名称已存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "云平台不存在!");
            }
            biPartition.setCreatorId(userId);
            biPartition.setGmtCreate(new Date());
            PartitionModel partitionModel = new PartitionModel(biPartition.getName());
            logger.info("create Partition start...");
            BocloudResult bocloudResult = f5PartitionDriver.create(vendor.getUuid(), partitionModel);
            if (bocloudResult.isSuccess()) {
                try {
                    f5BiPartitionRepository.save(biPartition);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return new BocloudResult(false, null, e.getMessage());
                }
                return new BocloudResult(true, "添加成功");
            } else {
                logger.error(bocloudResult.getMessage());
                return new BocloudResult(false, null, bocloudResult.getMessage());
            }
        } catch (Exception e) {
            logger.error("create Partition 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), "请求超时");
            BiPartition biPartition = this.f5BiPartitionRepository.query(id);
            if (null == biPartition) {
                return new BocloudResult(false, "请求内容不存在");
            }
            CloudVendor vendor = cloudVendorRepository.query(biPartition.getVendorId());
            if (null == vendor) {
                logger.error("get cloudVendor failure!");
                return new BocloudResult(false, "删除失败!");
            }
            logger.info("remove Partition start...");
            BocloudResult result = f5PartitionDriver.remove(vendor.getUuid(), biPartition.getName());
            if (result.isSuccess()) {
                try {
                    f5BiPartitionRepository.remove(id, userId);
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return new BocloudResult(false, null, e.getMessage());
                }
                return new BocloudResult(true, "删除成功");
            } else {
                logger.error(result.getMessage());
                return new BocloudResult(false, null, result.getMessage());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return new BocloudResult(false, "删除失败");
        }
    }

}
