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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.client.admin.common.utils.DateUtils;
import com.liquidnet.client.admin.zhengzai.kylin.utils.TaobaoTicketUtils;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
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.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;


/**
 * <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 RedisUtil redisUtil;

    @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));

            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
                obj1.setCityId(Long.parseLong(redisUtil.getDB15RedisHGet(KylinRedisConst.FIELDS + ":" + performanceRelationData.getFieldId(), "ad_code").toString()));
            }
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());
            Long venueId = sycField(performanceId, performanceRelationData.getFieldId());
            if (venueId != 0) {
                obj1.setVenueId(venueId);
            }
            req.setPushProjectParam(obj1);
            log.info("[同步演出] 演出名称 = " + performanceData.getTitle() + " 大麦演出id =" + performanceKey);
            AlibabaDamaiMevOpenPushprojectResponse rsp = client.execute(req);
            log.info("[BODY = {}]", rsp.getBody());
            if (rsp.getResult().getSuccess()) {
                List<KylinTicketTimeRelation> timeRelation = ticketTimeRelationMapper.selectList(new UpdateWrapper<KylinTicketTimeRelation>().eq("performance_id", performanceId));
                for (int i = 0; i < timeRelation.size(); i++) {
                    KylinTicketTimes timeData = ticketTimesMapper.selectOne(new UpdateWrapper<KylinTicketTimes>().eq("ticket_times_id", timeRelation.get(i).getTimesId()));
                    boolean result = sycTimes(performanceKey, timeData, venueId);
                    if (!result) {
                        return false;
                    }
                }
                log.info("[ 同步大麦-完成 ]");
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Long sycField(String performanceId, 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;
//            }
            obj1.setVenueId(Long.parseLong(redisUtil.getDB15RedisHGet(KylinRedisConst.FIELDS + ":" + fieldId, "id").toString()));
            obj1.setVenueName(redisUtil.getDB15RedisHGet(KylinRedisConst.FIELDS + ":" + fieldId, "name").toString());
            obj1.setVenueAddress(redisUtil.getDB15RedisHGet(KylinRedisConst.FIELDS + ":" + fieldId, "address").toString());

            req.setPushVenueParam(obj1);
            AlibabaDamaiMevOpenPushvenueResponse rsp = client.execute(req);
            log.info("[同步场地] 场地名称 = " + obj1.getVenueName() + " 大麦场地id =" + obj1.getVenueId());
            log.info("[BODY = {}]", rsp.getBody());
            if (!rsp.getResult().getSuccess()) {
                return 0L;
            }
            return obj1.getVenueId();
        } catch (Exception e) {
            e.printStackTrace();
            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().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()) {
                List<KylinTicketRelations> ticketRelation = ticketRelationsMapper.selectList(new UpdateWrapper<KylinTicketRelations>().eq("times_id", timesData.getTicketTimesId()));
                for (int i = 0; i < ticketRelation.size(); i++) {
                    if (null != ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketRelation.get(i).getTicketId()).eq("sync_damai", 1))) {
                        KylinTickets ticketData = ticketsMapper.selectOne(new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketRelation.get(i).getTicketId()));
                        boolean result = sycTicket(ticketTimesKey, ticketData);
                        if (!result) {
                            return false;
                        }
                    }
                }
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            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);
            if (rsp.getResult().getSuccess()) {
                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("[同步票种] 票种名称 = " + ticketsData.getTitle() + "-登登登VIP 大麦票种id =" + ticketIdKey + " 票种价格 = " + ticketsData.getPrice());
                AlibabaDamaiMevOpenPushitemResponse rsp2 = client2.execute(req2);
                if (rsp2.getResult().getSuccess()) {
                    return sycOrder(timemId, ticketsData.getTicketsId(), ticketIdKey,ticketIdKey2);
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean sycOrder(long timemId, String ticketsId, long ticketsmId,long ticketIdMemberKey) {
        try {
            TaobaoClient client = taobaoTicketUtils.initTaobaoClient();
            AlibabaDamaiMevOpenBatchpushticketRequest req = new AlibabaDamaiMevOpenBatchpushticketRequest();
            List<OrderPushDamaiDto> data = orderTicketsMapper.pushDamaiDetailsList(ticketsId);
            log.info("[同步订单] 票种张数 = " + data.size() + " 票种id =" + ticketsId);
            int forSize = 100;
            int forCount = data.size() % forSize == 0 ? data.size() / forSize : (data.size() / forSize) + 1;
            for (int i = 0; i < forCount; i++) {
                List<ThirdTicketPushOpenParam> list2 = new ArrayList<>();
                for (int y = 0; y < forSize; y++) {
                    if ((i * forSize + y) == data.size()) {
                        break;
                    }
                    OrderPushDamaiDto item = data.get(i * forSize + y);
                    ThirdTicketPushOpenParam obj3 = new ThirdTicketPushOpenParam();
                    long orderTicketEntitiesKey;
                    if (item.getIsMember() == 1) {
                        orderTicketEntitiesKey = Long.valueOf(IDGenerator.getDamaiCode(item.getOrderTicketEntitiesId()).toString().concat("010"));
                    } else {
                        orderTicketEntitiesKey = Long.valueOf(IDGenerator.getDamaiCode(item.getOrderTicketEntitiesId()).toString().concat("020"));
                    }

                    long orderIdKey = IDGenerator.getDamaiCode(item.getOrderTicketsId());
                    if (item.getIsPayment() == 3 || item.getIsPayment() == 2) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                    } else if (item.getTransferStatus() == 2 || item.getTransferStatus() == 6) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                    } else {
                        if (item.getEnterType() == 0 && !item.getEnterName().equals("")) {
                            log.info("[入场人错误数据] 入场人id = " + item.getOrderTicketEntitiesId() + " 入场人 name = " + item.getEnterName());
                        }
                        list2.add(obj3);
                        obj3.setUserName(item.getEnterName());//用户名 入场人姓名
                        obj3.setCertificateNo(item.getEnterIdCode());//证件号 入场人身份证
                        obj3.setOrderUserMobile(item.getEnterMobile());//用户手机号 入场人手机号
                        obj3.setCertificateType(item.getEnterType().longValue());//证件内容 入场人证件type
                        obj3.setPayTime(DateUtils.parseDate(item.getTimePay()));//支付时间
                        obj3.setPerformId(timemId);//场次id
                        if(item.getIsMember()==1){
                            obj3.setExt("登登登VIP");
                            obj3.setTicketItemId(ticketIdMemberKey);
                        }else{
                            obj3.setExt("登登登VIP");
                            obj3.setTicketItemId(ticketsmId);
                        }
                        obj3.setQrCode("http://m.zhengzai.tv?c="+IDGenerator.ticketQrCode(item.getOrderTicketEntitiesId()));
                        obj3.setVoucherId(orderTicketEntitiesKey);//票单号 入场人id
                        obj3.setOrderId(orderIdKey);//订单id orderId
                        obj3.setMediumType(item.getGetTicketType().equals("express") ? 1L : 2L);//票类型 快递 电子
                        obj3.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
                        obj3.setSystemId(taobaoTicketUtils.getSystemId());
                        obj3.setSeatType(1L);
                        obj3.setTicketType(1L);//票类型
                    }
                }
                req.setThirdTicketSetOpenParamList(list2);
                if (list2.size() == 0) {
                    return true;
                } else {
                    AlibabaDamaiMevOpenBatchpushticketResponse rsp = client.execute(req);
//                    log.info("order = " + rsp.getBody());
                    if (!rsp.getResult().getSuccess()) {
                        return false;
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
