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

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.compute.AvailabilitySetDriver;
import com.bocloud.cmp.model.NotifyMessage;
import com.bocloud.cmp.model.azure.AvailabilitySetModel;
import com.bocloud.cmp.params.azure.UserAssignParams;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.ListTool;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.common.enums.azure.AzureTaskStatus;
import com.bocloud.ims.entity.common.Project;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.ResourceGroup;
import com.bocloud.ims.entity.resource.azure.AvailabilitySet;
import com.bocloud.ims.interfaces.resource.azure.AvailabilitySetService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ResourceGroupRepository;
import com.bocloud.ims.repository.resource.azure.AvailabilitySetRepository;
import com.bocloud.ims.service.internal.SmsProjectService;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.service.lock.BocloudACLock;
import com.bocloud.service.lock.LockFactory;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class AvailabilitySetServiceImpl implements AvailabilitySetService {

    private static OperateResult.OperateCategory operateCategory = OperateResult.OperateCategory.ResourceEvent;

    private static Logger logger = LoggerFactory.getLogger(AvailabilitySetServiceImpl.class);
    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private AvailabilitySetRepository availabilitySetRepository;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private AvailabilitySetDriver availabilitySetDriver;
    @Autowired
    private ResourceGroupRepository resourceGroupRepository;
    @Autowired
    private SmsProjectService smsProjectService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public BocloudResult<GridBean<AvailabilitySet>> list(Pager pager, RequestContext context) {
        List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
        Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
        sorter.put("gmtCreate", Common.ONE);
        Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
        Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
        Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);

        try {
            List<AvailabilitySet> list;
            int total;
            GridBean<AvailabilitySet> gridBean;
            Long tenantId = context.getTenant();
            Long projectId = context.getProject();

            // 为租户下的用户
            if (null != tenantId && 0L != tenantId) {
                List<Project> projects = smsProjectService.projectsByCondition(context.getTarget(),
                        context.getCatalog());
                List<Long> projectIds = new ArrayList<>();
                // 此时查询的是全部用户全部项目的信息
                if (null != projectId && 0L != projectId) {
                    projectIds.add(projectId);
                } else if (!ListTool.isEmpty(projects)) {
                    projects.forEach(project -> projectIds.add(project.getId()));
                } else {
                    projectIds.add(-1L);
                }
                total = this.availabilitySetRepository.count(params, null, projectIds, null);
                list = this.availabilitySetRepository.list(page, rows, params, sorter, null, projectIds, null);
            } else {
                list = availabilitySetRepository.list(page, rows, params, sorter);
                total = availabilitySetRepository.count(params);
            }
            gridBean = new GridBean<>(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list availability set failure:", e);
            return new BocloudResult<>(false, "查询失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult create(AvailabilitySet entityParams, RequestContext context) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(entityParams.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            if (null != availabilitySetRepository.getByName(entityParams.getVendorId(), entityParams.getResourceGroupId(), entityParams.getName())) {
                return new BocloudResult(false, "名称已存在");
            }
            ResourceGroup resourceGroup = resourceGroupRepository.query(entityParams.getResourceGroupId());
            Assert.notNull(resourceGroup, "资源组不能为空");
            AvailabilitySetModel model = new AvailabilitySetModel();
            BeanUtils.copyProperties(entityParams, model);
            model.setResourceGroupName(resourceGroup.getName());

            //设置状态
            entityParams.setCreatorId(context.getTarget());
            entityParams.setResourceGroupId(resourceGroup.getId());
            entityParams.setTenantId(context.getTenant());
            entityParams.setProjectId(context.getProject());
            if (context.getCatalog() == RequestContext.Catalog.User) {
                entityParams.setUserId(context.getTarget());
            }
            entityParams.setStatus(AzureTaskStatus.BUILDING.name());
            availabilitySetRepository.save(entityParams);

            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".availabilitySet";
                String message;
                BocloudResult result = availabilitySetDriver.create(vendor.getUuid(), entityParams.getRegionId(),
                        model);
                if (result.isSuccess()) {
                    message = "尊敬的客户，您好！您的可用性集【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建成功，请登录控制台查看及管理。";
                    AvailabilitySetModel newModel = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),
                            AvailabilitySetModel.class);
                    BeanUtils.copyProperties(newModel, entityParams);
                    entityParams.setStatus(AzureTaskStatus.AVAILABLE.name());
                    availabilitySetRepository.update(entityParams);
                } else {
                    logger.error("创建可用性集失败：" + result.getMessage());
                    message = "尊敬的客户，您好！您的可用性集【" + entityParams.getName() + "】于" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "创建失败，失败信息：" + result.getMessage();
                    availabilitySetRepository.remove(entityParams.getId(), context.getTarget());
                }
                resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                        MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                //站内信推送
                NotifyMessage notifyMessage = new NotifyMessage(context, "可用性集:", message, null,
                        true, false);
                amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
            });
            return new BocloudResult(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("create availabilitySet error:", e);
            return new BocloudResult(false, "创建可用性集失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult remove(Long id, RequestContext context) {
        String path = AvailabilitySet.class.getSimpleName() + "_" + id;
        try (BocloudACLock lock = lockFactory.getACLock(path)) {
            Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
            AvailabilitySet entity = availabilitySetRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            CloudVendor vendor = cloudVendorRepository.query(entity.getVendorId());
            Assert.notNull(vendor, "平台验证失败");
            entity.setStatus(AzureTaskStatus.DELETING.name());
            availabilitySetRepository.update(entity);
            // todo 应校验云主机是否绑定该可用性集
            taskExecutor.execute(() -> {
                String operate = vendor.getType().toLowerCase() + ".availabilitySet";
                String message = "删除可用性集失败";

                BocloudResult result = availabilitySetDriver.remove(vendor.getUuid(), entity.getRegionId(),
                        entity.getUuid());
                try {
                    if (result.isSuccess()) {
                        message = "删除可用性集成功";
                        availabilitySetRepository.remove(id, context.getTarget());
                    } else {
                        logger.error("删除可用性集失败：" + result.getMessage());
                        message = result.getMessage();
                    }
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                    //站内信推送
                    NotifyMessage notifyMessage = new NotifyMessage(context, "提示:", message, null,
                            true, false);
                    amqpTemplate.convertAndSend("event.notice.queue", notifyMessage);
                } catch (Exception e) {
                    logger.error("remove availabilitySet fail:", e);
                    resourceEventPublisher.send(new OperateResult(result.isSuccess(), message, operate,
                            MapTools.simpleMap("vendorId", vendor.getId()), operateCategory, context));
                }
            });
            return new BocloudResult(true, "任务已下发，正在执行...");
        } catch (Exception e) {
            logger.error("remove availabilitySet fail:", e);
            return new BocloudResult(false, "删除可用性集失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<AvailabilitySet> detail(Long id, RequestContext context) {
        try {
            AvailabilitySet entity = availabilitySetRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            return new BocloudResult<>(true, entity, "查询详情成功");
        } catch (Exception e) {
            logger.error("query availability set detail fail:", e);
            return new BocloudResult<>(false, "查询详情失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<AvailabilitySet> assign(UserAssignParams params, RequestContext context) {
        // 资源ID
        Long id = params.getId();
        // 租户用户ID
        Long userId = params.getUserId();
        // 租户用户所在项目
        Long projectId = params.getProjectId();
        Long tenantId = params.getTenantId();
        try {
            AvailabilitySet entity = availabilitySetRepository.query(id);
            Assert.notNull(entity, "数据不存在");
            entity.setTenantId(tenantId);
            entity.setProjectId(projectId);
            entity.setUserId(userId);
            availabilitySetRepository.update(entity);
            return new BocloudResult<>(true, entity, "操作成功");
        } catch (Exception e) {
            logger.error("assign availabilitySet  fail:", e);
            return new BocloudResult<>(false, "操作失败:" + e.getMessage());
        }
    }

    @Override
    public BocloudResult<Void> assignBatch(UserAssignParams params, RequestContext context) {
        Long userId = params.getUserId();
        // 租户用户所在项目
        Long projectId = params.getProjectId();
        Long tenantId = params.getTenantId();
        List<Long> ids = params.getIds();
        for (Long id : ids) {
            UserAssignParams newParams = new UserAssignParams();
            newParams.setId(id);
            newParams.setUserId(userId);
            newParams.setTenantId(tenantId);
            newParams.setProjectId(projectId);
            this.assign(newParams, context);
        }
        return new BocloudResult<>(true, "操作成功");
    }
}
