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.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.taobao.api.TaobaoClient;
import com.taobao.api.internal.util.StringUtils;
import com.taobao.api.request.AlibabaDamaiMevOpenBatchpushticketRequest;
import com.taobao.api.request.AlibabaDamaiMevOpenBatchpushticketRequest.ThirdTicketPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushitemRequest;
import com.taobao.api.request.AlibabaDamaiMevOpenPushitemRequest.PushTicketItemPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushperformRequest;
import com.taobao.api.request.AlibabaDamaiMevOpenPushperformRequest.ThirdPerformPushOpenParam;
import com.taobao.api.request.AlibabaDamaiMevOpenPushprojectRequest;
import com.taobao.api.request.AlibabaDamaiMevOpenPushprojectRequest.ThirdProjectPushOpenParam;
import com.taobao.api.response.AlibabaDamaiMevOpenBatchpushticketResponse;
import com.taobao.api.response.AlibabaDamaiMevOpenPushitemResponse;
import com.taobao.api.response.AlibabaDamaiMevOpenPushperformResponse;
import com.taobao.api.response.AlibabaDamaiMevOpenPushprojectResponse;
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 KylinTicketTimesMapper ticketTimesMapper;
    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;
    @Autowired
    private KylinTicketsMapper ticketsMapper;
    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;
    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;

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

            obj1.setPicUrl(performanceData.getImgPoster());

            long performanceKey = IDGenerator.getDamaiCode(performanceData.getPerformancesId());
            obj1.setProjectId(performanceKey);
            obj1.setProjectName(performanceData.getTitle());
            obj1.setCityId(performanceData.getCityId().longValue());
            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()) {
                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);
                    if (!result) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

            obj1.setEndTime(StringUtils.parseDateTime(timesData.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            long ticketTimesKey = IDGenerator.getDamaiCode(timesData.getTicketTimesId());
            obj1.setPerformId(ticketTimesKey);
            obj1.setPerformName(timesData.getTitle());
            obj1.setProjectId(performancesmId);
            obj1.setStartTime(StringUtils.parseDateTime(timesData.getUseStart().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());
            obj1.setPerformId(timemId);
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());
//            obj1.setRemark("0");
            req.setPushItemParam(obj1);
            log.info("[同步票种] 票种名称 = " + ticketsData.getTitle() + " 大麦票种id =" + ticketIdKey);
            AlibabaDamaiMevOpenPushitemResponse rsp = client.execute(req);
            if (rsp.getResult().getSuccess()) {
                return sycOrder(timemId, ticketsData.getTicketsId(), ticketIdKey);
//                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public Boolean sycOrder(long timemId, String ticketsId, long ticketsmId) {
        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) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                    } else if (item.getTransferStatus() == 2 || item.getTransferStatus() == 6) {
                        taobaoTicketUtils.withdrawDamaiOrder(timemId, orderTicketEntitiesKey);
                    } else {
                        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
                        obj3.setTicketItemId(ticketsmId);
                        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;
        }
    }
}
