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.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
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
public class KylinDamaiServiceImpl extends ServiceImpl<KylinRoadShowsMapper, KylinRoadShows> implements DamaiService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @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 sycField(String fieldId) {
        return null;
    }

    @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());
            obj1.setProjectId(Long.valueOf(performanceData.getPerformancesId().substring(0, 5).concat(performanceData.getPerformancesId().substring(7, 12))));
            obj1.setProjectName(performanceData.getTitle());
            obj1.setCityId(performanceData.getCityId().longValue());
            obj1.setSupplierSecret(taobaoTicketUtils.getSupplierSecret());
            obj1.setSystemId(taobaoTicketUtils.getSystemId());

            req.setPushProjectParam(obj1);
            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(Long.valueOf(performanceData.getPerformancesId().substring(0, 5).concat(performanceData.getPerformancesId().substring(7, 12))), 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"))));
            obj1.setPerformId(Long.valueOf(timesData.getTicketTimesId().substring(0, 5).concat(timesData.getTicketTimesId().substring(7, 12))));
            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);
            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(Long.valueOf(timesData.getTicketTimesId().substring(0, 5).concat(timesData.getTicketTimesId().substring(7, 12))), 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();

            obj1.setItemId(Long.valueOf(ticketsData.getTicketsId().substring(0, 5).concat(ticketsData.getTicketsId().substring(7, 12))));
            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);
            AlibabaDamaiMevOpenPushitemResponse rsp = client.execute(req);
            if (rsp.getResult().getSuccess()) {
                return sycOrder(timemId, ticketsData.getTicketsId(), Long.valueOf(ticketsData.getTicketsId().substring(0, 5).concat(ticketsData.getTicketsId().substring(7, 12))));
            } 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<ThirdTicketPushOpenParam> list2 = new ArrayList<>();
            List<OrderPushDamaiDto> data = orderTicketsMapper.pushDamaiDetailsList(ticketsId);

            for (int i = 0; i < data.size(); i++) {
                OrderPushDamaiDto item = data.get(i);

                if (item.getStatus() == 4) {
                    taobaoTicketUtils.withdrawDamaiOrder(timemId + "", item.getOrderTicketEntitiesId());
                } else {
                    ThirdTicketPushOpenParam obj3 = new ThirdTicketPushOpenParam();
                    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);
                    if (item.getIsMember() == 1) {
                        obj3.setTicketItemId(Long.parseLong(ticketsmId + "010"));//票品id ticketId+01会员 ticketId+0非会员
                    } else {
                        obj3.setTicketItemId(Long.parseLong(ticketsmId + "020"));
                    }

                    obj3.setOrderId(Long.parseLong(item.getOrderTicketsId()));//订单id orderId
                    obj3.setVoucherId(Long.valueOf(item.getOrderTicketEntitiesId().substring(0, 5).concat(item.getOrderTicketEntitiesId().substring(7, 12))));//票单号 入场人id

                    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);
                return rsp.getResult().getSuccess();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
