package com.bocloud.ims.service.resource;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.common.TaskMsgDriver;
import com.bocloud.cmp.model.TaskMsgModel;
import com.bocloud.common.model.*;
import com.bocloud.common.utils.Common;
import com.bocloud.common.utils.GridHelper;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.common.VendorSyncRecord;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.VendorTaskMsg;
import com.bocloud.ims.interfaces.resource.SyncService;
import com.bocloud.ims.interfaces.resource.TaskMsgService;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.TaskMsgRepository;
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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

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

/**
 * 查询vc平台任务
 *
 * @ClassName: TaskMsgServiceImpl.java
 * @Description:
 * @author: ymh
 * @date: 2021年4月30日 上午11:50:38
 */
@Service
public class TaskMsgServiceImpl implements TaskMsgService {

    private static Logger logger = LoggerFactory.getLogger(TaskMsgServiceImpl.class);

    @Autowired
    private CloudVendorRepository cloudVendorRepository;
    @Autowired
    private TaskMsgDriver taskMsgDriver;
    @Autowired
    private TaskMsgRepository taskMsgRepository;
    @Autowired
    private SyncService syncService;
    @Autowired
    private LockFactory lockFactory;
    @Autowired
    private ResourceEventPublisher resourceEventPublisher;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public BocloudResult<List<TaskMsgModel>> list(Long vendorId) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(vendor, "云平台不存在");
            BocloudResult bocloudResult = taskMsgDriver.list(vendor.getUuid());
            if (bocloudResult.isFailed()) {
                return bocloudResult;
            }
            List<TaskMsgModel> taskMsgModels = (List<TaskMsgModel>) bocloudResult.getData();
            Collections.sort(taskMsgModels, new Comparator<TaskMsgModel>() {
                @Override
                public int compare(TaskMsgModel model1, TaskMsgModel model2) {
                    if (null != model2 && null != model1 && null != model2.getStartTime()
                            && null != model1.getStartTime()) {
                        return (int) (model2.getStartTime().getTime() - model1.getStartTime().getTime());
                    }
                    return 0;
                }
            });
            return new BocloudResult<>(true, taskMsgModels, "查询成功");
        } catch (Exception e) {
            logger.error("查询平台任务异常：" + e.getMessage());
            return new BocloudResult<>(false, "查询平台任务异常：" + e.getMessage());
        }
    }

    @Override
    public BocloudResult historyList(Long vendorId, Pager pager, RequestContext context) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(vendor, "云平台不存在");
            List<Param> params = Optional.ofNullable(pager.getParams()).orElse(new ArrayList<>());
            Map<String, String> sorter = Optional.ofNullable(pager.getSorter()).orElse(Maps.newHashMap());
            Boolean simple = Optional.ofNullable(pager.getSimple()).orElse(false);
            sorter.put("start_time", Common.ONE);
            Integer page = Optional.ofNullable(pager.getPage()).orElse(1);
            Integer rows = Optional.ofNullable(pager.getRows()).orElse(10);
            int total = taskMsgRepository.count(params);
            List<VendorTaskMsg> list = taskMsgRepository.list(page, rows, params, sorter);
            GridBean gridBean = GridHelper.getBean(page, rows, total, list);
            return new BocloudResult<>(true, gridBean, "查询成功");
        } catch (Exception e) {
            logger.error("list cloudVendor fail:", e);
            return new BocloudResult<>(false, "查询失败");
        }
    }

    @Override
    public BocloudResult syncVendorTaskMsg(Long vendorId, RequestContext context) {
        try {
            CloudVendor vendor = cloudVendorRepository.query(vendorId);
            Assert.notNull(vendor, "云平台不存在");
            // 启动一个线程
            new Thread(() -> {
                Date startTime = new Date();
                String path = CloudVendor.class.getSimpleName() + "_" + vendor.getId();
                String operate = vendor.getType().toLowerCase() + ".sync";
                BocloudResult result = new BocloudResult(false, "暂不支持");
                OperateResult operateResult = new OperateResult(true, "平台下历史任务同步成功", operate,
                        MapTools.simpleMap("vendorId", vendor.getId()), OperateResult.OperateCategory.ResourceEvent, context);
                try (BocloudACLock lock = lockFactory.getACLock(path)) {
                    Assert.isTrue(lock.acquire(10, TimeUnit.SECONDS), "请求超时");
                    syncService.syncContentVendorTaskMsg(vendorId);
                } catch (Exception e) {
                    logger.error("平台下历史任务同步任务异常", e);
                    operateResult.setSuccess(false);
                    operateResult.setMessage("平台下历史任务同步异常");
                }
                resourceEventPublisher.send(operateResult);
                VendorSyncRecord record = new VendorSyncRecord();
                record.setVendorId(vendor.getId());
                record.setStartTime(startTime);
                record.setEndTime(new Date());
                record.setCost(record.getEndTime().getTime() - startTime.getTime());
                record.setResult(operateResult.getMessage());
                record.setCreatorId(context.getTarget());
                record.setSyncResult(operateResult.isSuccess());
                record.setAuto(false);
                amqpTemplate.convertAndSend("vendor.record.queue", record);
                if (operateResult.isSuccess()) {
                    // 发送给云平台统计队列对云平台重新统计
                    JSONObject object = new JSONObject();
                    object.put(Common.VENDORID, vendor.getId());
                    amqpTemplate.convertAndSend("vendor.statistics.queue", object);
                }
                // 更新云平台最后一次同步时间
                vendor.setGmtModify(record.getEndTime());
                vendor.setMenderId(context.getTarget());
                cloudVendorRepository.update(vendor);

            }).start();
            return new BocloudResult(true, "同步任务已经下发，正在执行……");
        } catch (Exception e) {
            logger.error("sync VendorTaskMsg operation exception ", e);
            return new BocloudResult(false, "同步失败!");
        }
    }
}
