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

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.SuperAccountUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.goblin.dto.vo.GoblinGoodsInfoVo;
import com.liquidnet.service.kylin.dto.param.WqTempParam;
import com.liquidnet.service.kylin.dto.vo.CheckData;
import com.liquidnet.service.kylin.dto.vo.KylinTimePerformanceVo;
import com.liquidnet.service.kylin.dto.vo.WqTempVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.service.IKylinTempService;
import com.liquidnet.service.kylin.utils.DataUtils;
import com.liquidnet.service.kylin.utils.ObjectUtil;
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.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 jiangxiulong
 * @since 2021-05-02
 */
@Service
@Slf4j
public class TempServiceImpl implements IKylinTempService {

    @Autowired
    DataUtils dataUtils;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseDto<Boolean> setWqRedis(String orderId) {
        try {
            dataUtils.setWqOrderId(orderId);
            return ResponseDto.success();
        } catch (Exception e) {
            log.error("ERROR 添加 万青订单id ", e);
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<Boolean> delWqRedis(String orderId) {
        try {
            dataUtils.delWqOrderId(orderId);
            return ResponseDto.success();
        } catch (Exception e) {
            log.error("ERROR 删除 万青订单id ", e);
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<Boolean> insertWqTempExpress(WqTempParam param) {
        try {
            String uid = CurrentUtil.getCurrentUid();
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(param.getOrderId());
            if (!SuperAccountUtils.isSuperAccount(uid, orderTicketVo.getUserId())) {
                return ResponseDto.failure(ErrorMapping.get("20003"));
            }
//            if (uid.equals("809406") || uid.equals("773650")) {
//            } else {
//                if (!orderTicketVo.getUserId().equals(uid)) {
//                    return ResponseDto.failure(ErrorMapping.get("20003"));
//                }
//            }

            Integer isTemp = dataUtils.getWqOrderId(param.getOrderId());
            if (isTemp == 0) {
                return ResponseDto.failure(ErrorMapping.get("20003"));
            }

            LocalDateTime now = LocalDateTime.now();
            //获取用户相关
            String expressContact = param.getName();
            String expressAddress = param.getProvince() + param.getCity() + param.getCounty() + param.getAddress();
            String expressPhone = param.getPhone();
            String city = param.getCity();
            String province = param.getProvince();
            String county = param.getCounty();

            WqTempVo vo = WqTempVo.getNew();
            vo.setAddress(expressAddress);
            vo.setCity(city);
            vo.setCounty(county);
            vo.setProvince(province);
            vo.setMailNo("");
            vo.setName(expressContact);
            vo.setOrderId(param.getOrderId());
            vo.setPhone(expressPhone);
            dataUtils.setWqOrderVo(vo);

            queueUtils.sendMsgByRedis(
                    MQConst.KylinQueue.SQL_TRANSFER.getKey(),
                    SqlMapping.get("kylin_order_express_ex.insert",
                            param.getOrderId(), expressContact, expressAddress,
                            province, city, county, expressPhone, now));
        } catch (Exception e) {
            log.error("ERROR 添加 万青快递 ", e);
            return ResponseDto.failure();
        }
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<WqTempVo> getWqTempExpress(String orderId) {
        String uid = CurrentUtil.getCurrentUid();
        KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderId);
        if (!SuperAccountUtils.isSuperAccount(uid, orderTicketVo.getUserId())) {
            return ResponseDto.failure(ErrorMapping.get("20003"));
        }
//        if (uid.equals("809406") || uid.equals("773650")) {
//        } else {
//            if (!orderTicketVo.getUserId().equals(uid)) {
//                return ResponseDto.failure(ErrorMapping.get("20003"));
//            }
//        }
        WqTempVo vo = dataUtils.getWqOrderVo(orderId);
        return ResponseDto.success(vo);
    }

    @Override
    public ResponseDto<Boolean> updateMailNo(String orderId, String mailNo) {
        try {
            LocalDateTime now = LocalDateTime.now();
            WqTempVo vo = dataUtils.getWqOrderVo(orderId);
            vo.setMailNo(mailNo);
            dataUtils.setWqOrderVo(vo);
            queueUtils.sendMsgByRedis(
                    MQConst.KylinQueue.SQL_TRANSFER.getKey(),
                    SqlMapping.get("kylin_order_express_ex.sendMail",
                            mailNo, now, orderId));
            return ResponseDto.success();
        } catch (Exception e) {
            log.error("ERROR 万青发货 ", e);
            return ResponseDto.failure();
        }
    }

    @Override
    public ResponseDto<List<CheckData>> getCheckData(String performance_id, String idcode, String[] ticket_ids) {
        List<CheckData> voList = ObjectUtil.checkDataArrayList();
        List<KylinOrderTicketEntitiesVo> dataList = mongoTemplate.find(Query.query(Criteria.where("performanceId").is(performance_id).and("ticketId").in(ticket_ids).and("enterIdCode").is(idcode))
                , KylinOrderTicketEntitiesVo.class, KylinOrderTicketEntitiesVo.class.getSimpleName());
        for (KylinOrderTicketEntitiesVo entitiesVo : dataList) {
            if (entitiesVo.getEnterIdCode().equals(idcode)) {
                CheckData vo = CheckData.getNew();
                vo.setCheck_status(entitiesVo.getStatus());
                vo.setCheck_time(entitiesVo.getCheckedAt());
                vo.setEnter_idcode(entitiesVo.getEnterIdCode());
                vo.setEnter_mobile(entitiesVo.getEnterMobile());
                vo.setEnter_name(entitiesVo.getEnterName());
                vo.setTicket_id(entitiesVo.getTicketId());
                vo.setTicket_name(entitiesVo.getTicketTitle());
                vo.setTicket_count(1);
                vo.setTicket_entity_id(entitiesVo.getOrderTicketEntitiesId());
                vo.setTicket_use_end(entitiesVo.getUseEnd());
                vo.setTicket_use_start(entitiesVo.getUseStart());
                vo.setTicket_type(vo.getTicket_use_end().equals(vo.getTicket_use_start()) ? 1 : 0);
                vo.setSelect_status(false);

                KylinPerformanceVo performanceData = dataUtils.getPerformanceVo(performance_id);
                for (int x = 0; x < performanceData.getTicketTimeList().size(); x++) {
                    KylinTicketTimesVo timeItem = performanceData.getTicketTimeList().get(x);
                    for (int y = 0; y < timeItem.getTicketList().size(); y++) {
                        KylinTicketVo ticketItem = timeItem.getTicketList().get(y);
                        if (ticketItem.getTicketsId().equals(entitiesVo.getTicketId())) {
                            vo.setTicket_price(ticketItem.getPrice().toString());
                            break;
                        }
                    }
                }
                voList.add(vo);
            }
        }
        return ResponseDto.success(voList);
    }

    @Override
    public ResponseDto<List<CheckData>> checkTicket(String performance_id, String idcode, String remarks, String[] ticket_ids, String check_time) {
        List<CheckData> voList = ObjectUtil.checkDataArrayList();
        List<KylinOrderTicketEntitiesVo> dataList = mongoTemplate.find(Query.query(Criteria.where("performanceId").is(performance_id).and("ticketId").in(ticket_ids).and("enterIdCode").is(idcode))
                , KylinOrderTicketEntitiesVo.class, KylinOrderTicketEntitiesVo.class.getSimpleName());
        for (KylinOrderTicketEntitiesVo entitiesVo : dataList) {
            if (entitiesVo.getEnterIdCode().equals(idcode)) {
                CheckData vo = CheckData.getNew();
                vo.setCheck_status(entitiesVo.getStatus());
                vo.setCheck_time(entitiesVo.getCheckedAt());
                vo.setEnter_idcode(entitiesVo.getEnterIdCode());
                vo.setEnter_mobile(entitiesVo.getEnterMobile());
                vo.setEnter_name(entitiesVo.getEnterName());
                vo.setTicket_id(entitiesVo.getTicketId());
                vo.setTicket_name(entitiesVo.getTicketTitle());
                vo.setTicket_count(1);
                vo.setTicket_entity_id("");
                vo.setTicket_use_end(entitiesVo.getUseEnd());
                vo.setTicket_use_start(entitiesVo.getUseStart());
                vo.setTicket_type(vo.getTicket_use_end().equalsIgnoreCase(vo.getTicket_use_start()) ? 1 : 0);
                vo.setSelect_status(false);

                KylinPerformanceVo performanceData = dataUtils.getPerformanceVo(performance_id);
                for (int x = 0; x < performanceData.getTicketTimeList().size(); x++) {
                    KylinTicketTimesVo timeItem = performanceData.getTicketTimeList().get(x);
                    for (int y = 0; y < timeItem.getTicketList().size(); y++) {
                        KylinTicketVo ticketItem = timeItem.getTicketList().get(y);
                        if (ticketItem.getTicketsId().equals(entitiesVo.getTicketId())) {
                            vo.setTicket_price(ticketItem.getPrice().toString());
                            break;
                        }
                    }
                }
                voList.add(vo);
            }
        }

        List<WriteModel<Document>> list = ObjectUtil.getWriteModelDocumentArrayList();
        LinkedList<Object[]> paramsList = CollectionUtil.linkedListObjectArr();
        voList.forEach(r -> {
            paramsList.add(new Object[]{1, "PDA" + "PDA", LocalDateTime.now(), r.getTicket_entity_id(), remarks});
            Document updateQuery = Query.query(Criteria.where("performanceId").is(performance_id).and("ticketId").in(ticket_ids).and("enterIdCode").is(idcode)).getQueryObject();
            Document updateDoc = new Document("status", 1)
                    .append("checkClient", "PDA")
                    .append("updatedAt", check_time)
                    .append("checkType", "PDA")
                    .append("checkedAt", check_time)
                    .append("checkUserId", "PDA");
            list.add(new UpdateOneModel<>(updateQuery, new Document("$set", updateDoc)));
        });
        BulkWriteResult bulkWriteResult = mongoTemplate.getCollection(KylinOrderTicketEntitiesVo.class.getSimpleName()).bulkWrite(list);
        if (bulkWriteResult.getModifiedCount() > 0) {
            queueUtils.sendMsgByRedis(MQConst.KylinQueue.SQL_STATION.getKey(),
                    SqlMapping.get("kylin_order_ticket_entities.update_status_bystation_pad", paramsList));
        } else {
            return ResponseDto.success();
        }
        return ResponseDto.success(voList);
    }
}
