package com.liquidnet.service.kylin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.kylin.dto.param.KylinStationCheckOrderParam;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.entity.KylinOrderTicketEntities;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketEntitiesMapper;
import com.liquidnet.service.kylin.service.IKylinOrderTicketEntitiesService;
import com.liquidnet.service.kylin.utils.DataUtils;
import com.mongodb.bulk.BulkWriteResult;
import com.mongodb.client.model.UpdateOneModel;
import com.mongodb.client.model.WriteModel;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 订单详情 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-20
 */
@Slf4j
@Service
public class KylinOrderTicketEntitiesServiceImpl extends ServiceImpl<KylinOrderTicketEntitiesMapper, KylinOrderTicketEntities> implements IKylinOrderTicketEntitiesService {
    @Autowired
    MongoConverter mongoConverter;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    DataUtils dataUtils;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateByStation(List<KylinStationCheckOrderParam> checkOrderParamList) {
//        // 根据验票用户ID分组
//        Map<String, List<KylinStationCheckOrderParam>> checkOrderByUserIdMap = checkOrderParamList.stream().collect(Collectors.groupingBy(KylinStationCheckOrderParam::getCheckUserId));
//
//        for (Map.Entry<String, List<KylinStationCheckOrderParam>> entry : checkOrderByUserIdMap.entrySet()) {
//            List<KylinStationCheckOrderParam> checkOrderByUserList = entry.getValue();
//
//            // 根据验票类型分组
//            Map<String, List<KylinStationCheckOrderParam>> checkOrderByCheckTypeMap = checkOrderByUserList.stream().collect(Collectors.groupingBy(KylinStationCheckOrderParam::getCheckType));
//        }

        LocalDateTime nowDt = LocalDateTime.now();
        String nowDtStr = DateUtil.format(nowDt, DateUtil.Formatter.yyyyMMddHHmmss);
        LinkedList<Object[]> paramsList = new LinkedList<>();
        List<WriteModel<Document>> list = new ArrayList<>();
        checkOrderParamList.forEach(r -> {
            KylinOrderTicketEntitiesVo updateVo = KylinOrderTicketEntitiesVo.getNew();
            updateVo.setCheckType(r.getCheckType());
            updateVo.setCheckedAt(r.getCheckedAt());
            updateVo.setCheckUserId(r.getCheckUserId());
            updateVo.setUpdatedAt(nowDtStr);
            updateVo.setStatus(1);

//            dataUtils.delOrderTicketEntitiesRedis(r.getTicketEntitiesId());

            paramsList.add(new Object[]{1, nowDtStr, r.getCheckedAt(), r.getCheckType(), r.getCheckUserId(), r.getTicketEntitiesId()});
            Document updateQuery = Query.query(Criteria.where("orderTicketEntitiesId").is(r.getTicketEntitiesId())).getQueryObject();
            list.add(new UpdateOneModel<Document>(updateQuery, new Document("$set", Document.parse(JsonUtils.toJson(updateVo)))));
        });
        BulkWriteResult bulkWriteResult = mongoTemplate.getCollection(KylinOrderTicketEntitiesVo.class.getSimpleName()).bulkWrite(list);
        log.info("bulkWriteResult:{}", JsonUtils.toJson(bulkWriteResult));



        // TODO: 2021/6/1 sql to mq
//        rabbitTemplate.convertAndSend(MQConst.EXCHANGES_LIQUIDNET_SQL, MQConst.ROUTING_KEY_SQL,
//                SqlMapping.get("kylin_order_ticket_entities.updateStatusByStation", paramsList));
    }
}
