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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.client.admin.zhengzai.kylin.utils.DataUtils;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.param.ticketSystem.*;
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.dto.vo.ticketSystem.OrderVo;
import com.liquidnet.service.kylin.dto.vo.ticketSystem.TicketPriceVo;
import com.liquidnet.service.kylin.dto.vo.ticketSystem.TicketVo;
import com.liquidnet.service.kylin.dto.vo.ticketSystem.TimesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static com.liquidnet.commons.lang.util.DateUtil.DTF_YMD_HMS;

@Service
public class InnerService {

    @Value("${liquidnet.service.platform.url}")
    private String platform;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    DataUtils dataUtils;

    //上报演出
    public List<String> reportP(KylinPerformanceVo vo, String approval, String sponsorId) {
        STInsertPerformanceParam insertPerformanceParam = STInsertPerformanceParam.getNew();
        insertPerformanceParam.setPerformanceId(vo.getPerformancesId());
        insertPerformanceParam.setPerformanceName(vo.getTitle());
        if (approval != null) {
            insertPerformanceParam.setApproval(approval);//TODO 批文号
        }
        insertPerformanceParam.setTypeId(vo.getType() == 101 ? 2002 : 2003);
        insertPerformanceParam.setPosterUrl(vo.getImgPoster());
        insertPerformanceParam.setSponsor(sponsorId);
        //场次相关
        List<TimesVo> timesVos = new ArrayList();
        List<KylinTicketTimesVo> kylinTimeVos = vo.getTicketTimeList();
        for (KylinTicketTimesVo item : kylinTimeVos) {
            TimesVo timesVo = TimesVo.getNew();
            timesVo.setSessionId(item.getTicketTimesId());
            timesVo.setSessionName(item.getTitle());
            timesVo.setHallCode("320412009");//TODO
            timesVo.setSessionStartTime(item.getUseStart());
            String endTime = LocalDateTime.parse(item.getUseEnd() == null ? timesVo.getSessionStartTime() : item.getUseEnd(), DTF_YMD_HMS).plusDays(1).minusSeconds(1L).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            timesVo.setSessionEndTime(endTime);
            timesVo.setHasSeat(0);
            timesVos.add(timesVo);
        }
        insertPerformanceParam.setSessionList(timesVos);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/st/performance/insert", JSON.toJSONString(insertPerformanceParam), header);
        ResponseDto<JSONObject> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<JSONObject>>() {
        });
        List<String> sessionCodeList = CollectionUtil.linkedListString();
        for (KylinTicketTimesVo item : kylinTimeVos) {
            JSONObject jobj = innerReturnVo.getData();
            String sessionCode = jobj.getString(item.getTicketTimesId());
            sessionCodeList.add(sessionCode);
            setSessionCode(item.getTicketTimesId(), sessionCode);
        }
        for (KylinTicketTimesVo item : vo.getTicketTimeList()) {
            reportTP(item.getTicketList(), getSessionCode(item.getTicketTimesId()), vo.getPerformancesId(), item.getTicketTimesId());
        }

        return sessionCodeList;
    }

    //修改上报的演出项目数据
    public boolean updateP(KylinTicketTimesVo vo, String performanceId, String sessionCode) {
        STUpdateTimesParam updateTimesParam = STUpdateTimesParam.getNew();
        updateTimesParam.setSessionId(vo.getTicketTimesId());
        updateTimesParam.setSessionCode(sessionCode);
        updateTimesParam.setSessionName(vo.getTitle());
        updateTimesParam.setSessionStartTime(LocalDateTime.parse(vo.getUseStart(), DTF_YMD_HMS));
        updateTimesParam.setSessionEndTime(LocalDateTime.parse(vo.getUseEnd(), DTF_YMD_HMS));
        updateTimesParam.setHallCode("320412009");//TODO
        updateTimesParam.setHasSeat(0);
        updateTimesParam.setPerformanceId(performanceId);
        updateTimesParam.setSessionStatus(1);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/performance/update", JSON.toJSONString(updateTimesParam), header);
        ResponseDto<Boolean> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<Boolean>>() {
        });
        return innerReturnVo.getData();
    }

    //更新上报的场次数据
    public boolean updateTT(KylinPerformanceVo vo, String approval, String sponsorId) {
        STUpdatePerformanceParam updatePerformanceParam = STUpdatePerformanceParam.getNew();
        updatePerformanceParam.setPerformanceId(vo.getPerformancesId());
        updatePerformanceParam.setPerformanceName(vo.getTitle());
        updatePerformanceParam.setTypeId(vo.getType() == 101 ? 2002 : 2003);
        updatePerformanceParam.setPosterUrl(vo.getImgPoster());
        updatePerformanceParam.setSponsor(sponsorId);
        updatePerformanceParam.setApproval(approval);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/times/update", JSON.toJSONString(updatePerformanceParam), header);
        ResponseDto<Boolean> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<Boolean>>() {
        });
        return innerReturnVo.getData();
    }

    //上报票价信息
    private boolean reportTP(List<KylinTicketVo> vo, String sessionCode, String performanceId, String ticketTimeId) {
        STInsertTicketPriceParam insertTicketPriceParam = STInsertTicketPriceParam.getNew();
        insertTicketPriceParam.setSessionCode(sessionCode);
        List<TicketPriceVo> priceVos = new ArrayList();
        for (KylinTicketVo item : vo) {
            TicketPriceVo priceVo = TicketPriceVo.getNew();
            priceVo.setPerformanceId(performanceId);
            priceVo.setSessionId(ticketTimeId);
            priceVo.setPriceId(getPriceId(item.getTicketsId()));
            priceVo.setPriceName(item.getTitle());
            priceVo.setTicketPrice(item.getPrice().multiply(BigDecimal.valueOf(100)).intValue());
            priceVo.setAvailableInventory(item.getTotalGeneral());//TODO 票量累加
            priceVo.setUnavailableInventory(0);//工作人员位置等 无座位无用
            priceVos.add(priceVo);
        }
        insertTicketPriceParam.setPriceList(priceVos);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/st/ticketPrice/insert", JSON.toJSONString(insertTicketPriceParam), header);
        ResponseDto<Boolean> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<Boolean>>() {
        });
        reportT(performanceId, getSessionCode(ticketTimeId), vo, ticketTimeId);
        return innerReturnVo.getData();
    }

    //上报票信息
    private boolean reportT(String performanceId, String sessionCode, List<KylinTicketVo> ticketIdList, String ticketTimeId) {
        STInsertTicketParam insertTicketParam = STInsertTicketParam.getNew();
        insertTicketParam.setPerformanceId(performanceId);
        insertTicketParam.setSessionId(ticketTimeId);
        insertTicketParam.setSessionCode(sessionCode);
        List<TicketVo> ticketVos = new ArrayList();
        for (KylinTicketVo item : ticketIdList) {
            insertTicketParam.setPriceId(getPriceId(item.getTicketsId()));
            TicketVo ticketVo = TicketVo.getNew();
            ticketVo.setTicketId(item.getTicketsId());
            ticketVo.setAvailableSale(1);
            ticketVos.add(ticketVo);
        }
        insertTicketParam.setTicketList(ticketVos);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/st/ticket/insert", JSON.toJSONString(insertTicketParam), header);
        ResponseDto<Boolean> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<Boolean>>() {
        });
        return innerReturnVo.getData();
    }

    //设置SessionCode
    private void setSessionCode(String ticketTimeId, String sessionCode) {
        redisUtil.set(KylinRedisConst.TIMES_SESSION_CODE.concat(ticketTimeId), sessionCode);
    }

    //获取SessionCode
    private String getSessionCode(String ticketTimeId) {
        return (String) redisUtil.get(KylinRedisConst.TIMES_SESSION_CODE.concat(ticketTimeId));
    }

    private String getPriceId(String ticketId) {
        return ticketId.concat("01");
    }


    //上报订单
    public boolean reportO(KylinOrderTicketVo vo, String channelName) {
        STInsertOrderParam insertOrderParam = STInsertOrderParam.getNew();
        insertOrderParam.setOrderId(vo.getOrderTicketsId());
        insertOrderParam.setOrderTime(vo.getTimePay());
        insertOrderParam.setChannelType(1);
        insertOrderParam.setChannelName(channelName);
        insertOrderParam.setTicketNum(vo.getNumber());
        insertOrderParam.setTotalAmount(vo.getPriceActual().multiply(BigDecimal.valueOf(100)).intValue());
        insertOrderParam.setTicketType(1);
        insertOrderParam.setTicketMode(vo.getGetTicketType().equalsIgnoreCase("express") ? 1 : 2);
        insertOrderParam.setAuthMode(dataUtils.getPerformanceIsTrueName(vo.getPerformanceId()) == 1 ? 3 : 1);
        int voucherPrice = vo.getPriceVoucher().multiply(BigDecimal.valueOf(100)).divide(BigDecimal.valueOf(vo.getNumber())).intValue();
        List<OrderVo> orderVos = new ArrayList();
        for (KylinOrderTicketEntitiesVo item : vo.getEntitiesVoList()) {
            OrderVo orderVo = OrderVo.getNew();
            orderVo.setTicketOrderId(item.getOrderTicketEntitiesId());
            orderVo.setPerformanceId(item.getPerformanceId());
            orderVo.setSessionId(item.getTimeId());
            orderVo.setSessionCode(getSessionCode(item.getTimeId()));
            orderVo.setPriceId(getPriceId(item.getTicketId()));
            orderVo.setTicketPrice(vo.getPrice().multiply(BigDecimal.valueOf(100)).intValue());
            orderVo.setTicketId(item.getTicketId());
            orderVo.setTicketOrderAmount(orderVo.getTicketPrice() - voucherPrice);
            orderVos.add(orderVo);
        }
        insertOrderParam.setTicketOrderList(orderVos);
        MultiValueMap<String, String> header = CollectionUtil.linkedMultiValueMapStringString();
        header.add("Accept", "application/json;charset=UTF-8");
        String resultData = HttpUtil.postRaw(platform + "/platform/st/order/insert", JSON.toJSONString(insertOrderParam), header);
        ResponseDto<Boolean> innerReturnVo = JsonUtils.fromJson(resultData, new TypeReference<ResponseDto<Boolean>>() {
        });
        return innerReturnVo.getData();
    }
}
