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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.mq.constant.MQConst;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.kylin.dto.param.KylinStationUploadParam;
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.QueueUtils;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

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  implements IKylinOrderTicketEntitiesService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    QueueUtils queueUtils;

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateByStation(KylinStationUploadParam parameter) {
//        // 根据验票用户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<>();
        parameter.getCheckOrderParamList().forEach(r -> {
            KylinOrderTicketEntitiesVo updateVo = KylinOrderTicketEntitiesVo.getNew();
            updateVo.setStatus(1);// 出票状态: 0未出票 1已出票
            updateVo.setCheckClient(parameter.getCheckClient());
            updateVo.setUpdatedAt(nowDtStr);
            updateVo.setCheckType(r.getCheckType());
            updateVo.setCheckedAt(r.getCheckedAt());
            updateVo.setCheckUserId(r.getCheckUserId());

            paramsList.add(new Object[]{1, updateVo.getCheckClient() + updateVo.getCheckType(), nowDt, r.getTicketEntitiesId()});
            Document updateQuery = Query.query(Criteria.where("orderTicketEntitiesId").is(r.getTicketEntitiesId())).getQueryObject();
            Document updateDoc = new Document("status", updateVo.getStatus())
                    .append("checkClient", updateVo.getCheckClient())
                    .append("updatedAt", updateVo.getUpdatedAt())
                    .append("checkType", updateVo.getCheckType())
                    .append("checkedAt", updateVo.getCheckedAt())
                    .append("checkUserId", updateVo.getUserId());
            list.add(new UpdateOneModel<Document>(updateQuery, new Document("$set", updateDoc)));
        });
        BulkWriteResult bulkWriteResult = mongoTemplate.getCollection(KylinOrderTicketEntitiesVo.class.getSimpleName()).bulkWrite(list);
        log.info("bulkWriteResult:{}", JsonUtils.toJson(bulkWriteResult));

        queueUtils.sendSqlRabbit(MQConst.EX_LNS_SQL_STATION, MQConst.RK_SQL_STATION,
                SqlMapping.get("kylin_order_ticket_entities.updateStatusByStation", paramsList));
    }
}
