package com.liquidnet.client.admin.zhengzai.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.DateUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.TaobaoTicketUtils;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.dao.OrderPushDamaiDto;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.other.DamaiService;
import com.liquidnet.service.slime.entity.SlimeFields;
import com.liquidnet.service.slime.mapper.SlimeFieldsMapper;
import com.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.*;
import com.taobao.api.request.AlibabaDamaiMevOpenBatchpushticketRequest.ThirdTicketPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushitemRequest.PushTicketItemPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushperformRequest.ThirdPerformPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushprojectRequest.ThirdProjectPushOpenParam;
import com.taobao.api.response.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 巡演 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-11
 */
@Service
@Slf4j
public class KylinDamaiServiceImpl extends ServiceImpl<KylinRoadShowsMapper, KylinRoadShows> implements DamaiService {

    @Autowired
    private TaobaoTicketUtils taobaoTicketUtils;
    @Autowired
    private KylinOrderTicketsMapper orderTicketsMapper;
    @Autowired
    private KylinPerformancesMapper performancesMapper;
    @Autowired
    private KylinPerformanceRelationsMapper performanceRelationsMapper;
    @Autowired
    private KylinTicketTimesMapper ticketTimesMapper;
    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;
    @Autowired
    private KylinTicketsMapper ticketsMapper;
    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;
    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;
    @Autowired
    private SlimeFieldsMapper slimeFieldsMapper;
    @Autowired
    private DataUtils dataUtils;

    @Override
    public Boolean sycPerformance(String performanceId) {
        try {
            // 大麦工具
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenPushprojectRequest req = new AlibabaDamaiMevOpenPushprojectRequest();
            ThirdProjectPushOpenParam obj1 = new ThirdProjectPushOpenParam();

            // 演出数据
            KylinPerformances performanceData = performancesMapper.selectOne(
                    new UpdateWrapper<KylinPerformances>().eq("performances_id", performanceId)
            );
            KylinPerformanceRelations performanceRelationData = performanceRelationsMapper.selectOne(
                    new UpdateWrapper<KylinPerformanceRelations>().eq("performance_id", performanceId)
            );

            // 同步场地信息
            Long venueId = sycField(performanceRelationData.getFieldId());
            if (venueId <= 0) {
                return false;
            }

            // 同步演出信息
            obj1.setVenueId(venueId);
            obj1.setPicUrl(performanceData.getImgPoster());
            long performanceKey = IDGenerator.getDamaiCode(performanceData.getPerformancesId());
            obj1.setProjectId(performanceKey);
            obj1.setProjectName(performanceData.getTitle());
            if (performanceData.getCityId().equals(6977)) {
                obj1.setCityId(110100L);
            } else if (performanceData.getCityId().equals(3833)) {
                obj1.setCityId(520100L);
            } else {//520100
                String cityId = dataUtils.getFieldsVoByFieldId(performanceRelationData.getFieldId()).getCityId();
                obj1.setCityId(Long.parseLong(cityId));
            }
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());
            req.setPushProjectParam(obj1);
            log.info("[同步演出] 演出名称 = " + performanceData.getTitle() + " 大麦演出id =" + performanceKey);
            AlibabaDamaiMevOpenPushprojectResponse rsp = client.execute(req);
            if (!rsp.getResult().getSuccess()) {
                log.error("[同步演出] res [BODY = {}]", rsp.getBody());
                return false;
            }

            // 同步场次
            List<KylinTicketTimeRelation> timeRelation = ticketTimeRelationMapper.selectList(
                    new UpdateWrapper<KylinTicketTimeRelation>().eq("performance_id", performanceId)
            );
            for (KylinTicketTimeRelation relation : timeRelation) {
                KylinTicketTimes timeData = ticketTimesMapper.selectOne(
                        new UpdateWrapper<KylinTicketTimes>().eq("ticket_times_id", relation.getTimesId())
                );
                boolean result = sycTimes(performanceKey, timeData, venueId);
                if (!result) {
                    return false;
                }
            }

            // 同步票种
            List<String> timeIdList = timeRelation.stream().map(KylinTicketTimeRelation::getTimesId).collect(Collectors.toList());
            List<KylinTicketRelations> ticketRelation = ticketRelationsMapper.selectList(
                    new UpdateWrapper<KylinTicketRelations>().in("times_id", timeIdList)
            );
            for (KylinTicketRelations ticketRelations : ticketRelation) {
                long ticketTimesKey = IDGenerator.getDamaiCode(ticketRelations.getTimesId());
                // 是否开启了同步的票种
//                KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(
//                        new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketRelations.getTicketId()).eq("sync_damai", 1)
//                );
//                if (null != ticketStatus) {
                KylinTickets ticketData = ticketsMapper.selectOne(
                        new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketRelations.getTicketId())
                );
                boolean result = sycTicket(ticketTimesKey, ticketData);
                if (!result) {
                    return false;
                }
//                }
            }

            // 同步订单
            for (KylinTicketRelations ticketRelations : ticketRelation) {
                long ticketTimesKey = IDGenerator.getDamaiCode(ticketRelations.getTimesId());
                long ticketIdKey = IDGenerator.getDamaiCode(ticketRelations.getTicketId());
                long ticketIdKey2 = Long.valueOf(ticketIdKey + "".concat("010"));
                boolean result = sycOrder(ticketTimesKey, ticketRelations.getTicketId(), ticketIdKey, ticketIdKey2);
                if (!result) {
                    return false;
                }
            }

            // 所有同步完成
            log.info("[ 同步大麦-完成 ]");
            return true;

        } catch (Exception e) {
            log.error("[同步大麦] 异常:{}", e);
            return false;
        }
    }

    public Long sycField(String fieldId) {
        try {
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenPushvenueRequest req = new AlibabaDamaiMevOpenPushvenueRequest();
            AlibabaDamaiMevOpenPushvenueRequest.ThirdVenuePushOpenParam obj1 = new AlibabaDamaiMevOpenPushvenueRequest.ThirdVenuePushOpenParam();
//        obj1.setPushTime(StringUtils.parseDateTime("2017-01-01 00:00:00"));
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());

//            if (performanceId.equals("299481167884001288936975")) {
//                obj1.setVenueId(2774011L);
//                obj1.setVenueName("北京世园公园");
////                obj1.setVenueAddress("foo");
//            } else if (performanceId.equals("5936257")) {
//                obj1.setVenueId(3238010L);
//                obj1.setVenueName("贵阳奥林匹克体育中心");
////                obj1.setVenueAddress("foo");
//            } else {
//                return 0L;
//            }
            SlimeFields slimeFields = slimeFieldsMapper.selectOne(
                    Wrappers.lambdaQuery(SlimeFields.class)
                            .eq(SlimeFields::getFieldId, fieldId)
            );
//            SlimeFieldsVo fieldsVo =  dataUtils.getFieldsVoByFieldId(fieldId);
            obj1.setVenueId(slimeFields.getMid());
            obj1.setVenueName(slimeFields.getName());
            obj1.setVenueAddress(slimeFields.getAddress());

            req.setPushVenueParam(obj1);
            log.info("[同步场地] 场地名称 = " + obj1.getVenueName() + " 大麦场地id =" + obj1.getVenueId());
            AlibabaDamaiMevOpenPushvenueResponse rsp = client.execute(req);
            if (!rsp.getResult().getSuccess()) {
                log.error("[同步场地] res [BODY = {}]", rsp.getBody());
                return 0L;
            }
            return obj1.getVenueId();
        } catch (Exception e) {
            log.error("[同步场地] 异常:{}", e);
            return 0L;
        }
    }

    @Override
    public Boolean sycTimes(long performancesmId, KylinTicketTimes timesData, Long venueId) {
        try {
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenPushperformRequest req = new AlibabaDamaiMevOpenPushperformRequest();
            ThirdPerformPushOpenParam obj1 = new ThirdPerformPushOpenParam();

            long ticketTimesKey = IDGenerator.getDamaiCode(timesData.getTicketTimesId());
            obj1.setPerformId(ticketTimesKey);
            obj1.setPerformName(timesData.getTitle());
            obj1.setProjectId(performancesmId);
            obj1.setVenueId(venueId);
            obj1.setStartTime(StringUtils.parseDateTime(timesData.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            obj1.setEndTime(StringUtils.parseDateTime(timesData.getUseEnd().plusDays(1).minusSeconds(1L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
//            obj1.setEndTime(StringUtils.parseDateTime(timesData.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());
            req.setPushPerformParam(obj1);
            log.info("[同步场次] 场次名称 = " + timesData.getTitle() + " 大麦场次id =" + ticketTimesKey);
            AlibabaDamaiMevOpenPushperformResponse rsp = client.execute(req);
            if (!rsp.getResult().getSuccess()) {
                log.error("[同步场次] res [BODY = {}]", rsp.getBody());
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("[同步场次] 异常:{}", e);
            return false;
        }
    }

    @Override
    public Boolean sycTicket(long timemId, KylinTickets ticketsData) {
        try {
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenPushitemRequest req = new AlibabaDamaiMevOpenPushitemRequest();
            PushTicketItemPushOpenParam obj1 = new PushTicketItemPushOpenParam();
            long ticketIdKey = IDGenerator.getDamaiCode(ticketsData.getTicketsId());
            obj1.setItemId(ticketIdKey);
            obj1.setItemName(ticketsData.getTitle());
            obj1.setItemPrice(ticketsData.getPrice().longValue() * 100);
            obj1.setPerformId(timemId);
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());
            req.setPushItemParam(obj1);
            log.info("[同步票种] 票种名称 = " + ticketsData.getTitle() + " 大麦票种id =" + ticketIdKey + " 票种价格 = " + ticketsData.getPrice());
            AlibabaDamaiMevOpenPushitemResponse rsp = client.execute(req);

            TaobaoClient client2 = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenPushitemRequest req2 = new AlibabaDamaiMevOpenPushitemRequest();
            PushTicketItemPushOpenParam obj12 = new PushTicketItemPushOpenParam();
            long ticketIdKey2 = Long.valueOf(ticketIdKey + "".concat("010"));
            obj12.setItemId(ticketIdKey2);
            obj12.setItemName(ticketsData.getTitle() + "-登登登VIP");
            obj12.setItemPrice(ticketsData.getPrice().longValue() * 100);
            obj12.setPerformId(timemId);
            obj12.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj12.setSystemId(taobaoTicketUtils.getSystemId());
            req2.setPushItemParam(obj12);
            log.info("[同步VIP票种] 票种名称 = " + obj12.getItemName() + " 大麦票种id =" + ticketIdKey2 + " 票种价格 = " + ticketsData.getPrice());
            AlibabaDamaiMevOpenPushitemResponse rsp2 = client2.execute(req2);

            if (!rsp.getResult().getSuccess() || !rsp2.getResult().getSuccess()) {
                log.error("[同步票种] res [BODY = {}]", rsp.getBody());
                log.error("[同步VIP票种] res [BODY = {}]", rsp2.getBody());
                return false;
            }
            return true;
        } catch (Exception e) {
            log.error("[同步票种] 异常:{}", e);
            return false;
        }
    }

    @Override
    public Boolean sycOrder(long timemId, String ticketsId, long ticketsmId, long ticketIdMemberKey) {
        try {
            ArrayList<Long> orderTicketEntitiesKeyList = new ArrayList();
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenBatchpushticketRequest req = new AlibabaDamaiMevOpenBatchpushticketRequest();
            List<OrderPushDamaiDto> data = orderTicketsMapper.pushDamaiDetailsList(ticketsId);
            int dataSize = data.size();
            log.info("[同步订单] 票种总张数 = " + dataSize + " 票种id =" + ticketsId);

            int batchSize = 100;
            int orderCount = 0;
            int refundOrderCount = 0;
            int transferRefundOrderCount = 0;
            for (int i = 0; i < dataSize; i += batchSize) {

                List<ThirdTicketPushOpenParam> paramList = new ArrayList<>();
                // 使用 subList 方法获取当前批次的数据子列表
                List<OrderPushDamaiDto> batch = data.subList(i, Math.min(i + batchSize, dataSize));

                for (OrderPushDamaiDto item : batch) {
                    ThirdTicketPushOpenParam obj3 = new ThirdTicketPushOpenParam();
                    String ticketEntitiesId = item.getOrderTicketEntitiesId();
                    // 生成大麦票单 id
                    long orderTicketEntitiesKey;
                    if (item.getIsMember() == 1) {
                        orderTicketEntitiesKey = Long.valueOf(IDGenerator.getDamaiCode(ticketEntitiesId).toString().concat("010"));
                    } else {
                        orderTicketEntitiesKey = Long.valueOf(IDGenerator.getDamaiCode(ticketEntitiesId).toString().concat("020"));
                    }

                    // 可能orderTicketEntitiesKey有重复的吧 判断重复的加 1 但是也不准确 会不会有多个重复的
                    orderTicketEntitiesKey = checkAndIncrement(orderTicketEntitiesKeyList, orderTicketEntitiesKey, "1", ticketEntitiesId);
                    orderTicketEntitiesKeyList.add(orderTicketEntitiesKey);

                    // 同步所有订单信息 已支付 退款中 已退款的
                    long orderIdKey = IDGenerator.getDamaiCode(item.getOrderTicketsId());
                    if (item.getEnterType() == 0 || item.getEnterName().equals("")) {
                        log.error("[入场人信息错误] OrderTicketEntitiesId = " + item.getOrderTicketEntitiesId()
                                + " 入场人 type = " + item.getEnterType() + " 入场人 name = " + item.getEnterName());
                        continue;
                    }
                    // 用户名 入场人姓名
                    obj3.setUserName(item.getEnterName());
                    // 证件号 入场人身份证
                    obj3.setCertificateNo(item.getEnterIdCode());
                    // 用户手机号 入场人手机号
                    obj3.setOrderUserMobile(item.getEnterMobile());
                    // 1大陆身份证 2港澳通行证 3台胞证 4护照 5军官证
                    // 证件内容 入场人证件type
                    // 大麦 1=身份证,2=学⽣证, 3=军官证，4=护照,5=港澳通⾏证，6=台胞证
                    switch (item.getEnterType()) {
                        case 1:
                            obj3.setCertificateType(1L);
                            break;
                        case 2:
                            obj3.setCertificateType(5L);
                            break;
                        case 3:
                            obj3.setCertificateType(6L);
                            break;
                        case 4:
                            obj3.setCertificateType(4L);
                            break;
                        case 5:
                            obj3.setCertificateType(3L);
                            break;
                        default:
                            log.error("[入场人类型错误] OrderTicketEntitiesId = " + item.getOrderTicketEntitiesId() + " 入场人 type = " + item.getEnterType());
                            continue;
                    }
                    // 支付时间
                    obj3.setPayTime(DateUtils.parseDate(item.getTimePay()));
                    // 场次id
                    obj3.setPerformId(timemId);
                    if (item.getIsMember() == 1) {
//                        obj3.setExt("登登登VIP");
                        obj3.setExt("");
                        obj3.setTicketItemId(ticketIdMemberKey);
                    } else {
                        obj3.setExt("");
//                        obj3.setExt("登登登VIP");
                        obj3.setTicketItemId(ticketsmId);
                    }
                    obj3.setQrCode("http://m.zhengzai.tv?c=" + IDGenerator.ticketQrCode(item.getOrderTicketEntitiesId()));
                    // 票单号 入场人id
                    obj3.setVoucherId(orderTicketEntitiesKey);
                    // 订单id orderId
                    obj3.setOrderId(orderIdKey);
                    // 票类型 快递 电子
                    obj3.setMediumType(item.getGetTicketType().equals("express") ? 1L : 2L);
                    obj3.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
                    obj3.setSystemId(taobaoTicketUtils.getSystemId());
                    obj3.setSeatType(1L);
                    //票类型
                    obj3.setTicketType(1L);

                    List<ThirdTicketPushOpenParam> paramList2 = new ArrayList<>();
                    paramList2.add(obj3);
                    req.setThirdTicketSetOpenParamList(paramList2);
                    AlibabaDamaiMevOpenBatchpushticketResponse rsp = client.execute(req);
                    if (!rsp.getResult().getSuccess()) {
                        log.error("[同步订单] res [BODY = {}]", rsp.getBody());
                        return false;
                    }

                    // 部分退款是不退的，但是阶梯退票客服手动申请的现在也是部分退款，用户自己申请的现在不确定
                    // 取消退款的貌似没处理 其实这块应该可以不用处理退款中的，因为印象中退款那里有接入同步大麦
                    // 0未支付 1已支付 2退款中 3已退款 4部分退款
                    if (item.getIsPayment() == 3 || item.getIsPayment() == 2 || item.getIsPayment() == 4) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                        refundOrderCount += 1;
                        // 已转赠是转出去了 被退回是被别人退回了 已退回是别人给我的我给退回了
                        // 0交易成功，1转增中，2已转赠，3转增订单，4待接收，5被退回 ,6已退回
                    } else if (item.getTransferStatus() == 2 || item.getTransferStatus() == 6) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                        transferRefundOrderCount += 1;
                    } else {
                        orderCount += 1;
                    }
                }

                /*if (paramList.size() == 0) {
                    return true;
                } else {
                    req.setThirdTicketSetOpenParamList(paramList);
                    AlibabaDamaiMevOpenBatchpushticketResponse rsp = client.execute(req);
                    if (!rsp.getResult().getSuccess()) {
                        log.error("[同步订单] res [BODY = {}]", rsp.getBody());
                        return false;
                    }
                }*/
            }

            int count = orderCount + transferRefundOrderCount + refundOrderCount;
            log.info("[同步订单] 同步成功总张数 = " + count
                    + " orderCount =" + orderCount + " refund =" + refundOrderCount + " transfer =" + transferRefundOrderCount + " 票种id =" + ticketsId);
            return true;
        } catch (Exception e) {
            log.error("[同步订单] 异常:{}", e);
            return null;
        }
    }

    private Long checkAndIncrement(List<Long> list, Long value, String suffix, String ticketEntitiesId) {
        // 如果列表中不包含该值，则返回该值
        if (!list.contains(value)) {
            return value;
        } else {
            log.error("[ order_ticket_entities_id重复 ] ticketEntitiesId = " + ticketEntitiesId);
            // 生成新的值
            Long newValue = Long.parseLong(value + suffix);
            // 递归调用，尝试新值
            return checkAndIncrement(list, newValue, suffix + "1", ticketEntitiesId);
        }
    }

    public static void main(String[] args) {
        Long a = IDGenerator.getDamaiCode("1360935572095672321307852");

        System.out.println(a);
    }
}
