package cn.freemud.service.impl;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.entities.vo.parking.ParkingOrderResponseVo;
import cn.freemud.entities.vo.parking.QueryParkingOrderVo;
import cn.freemud.entities.vo.parking.QueryParkingOrdersResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.service.ParkingOrderService;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSONObject;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.enums.OrderClientType;
import com.freemud.application.sdk.api.ordercenter.request.OrderConditionsReq;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.response.BaseDownLoadResponse;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderSettlementResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderDownLoadSdkService;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
import com.freemud.application.sdk.api.paymentcenter.client.request.PaymentQueryOrderRequest;
import com.freemud.application.sdk.api.paymentcenter.client.response.PaymentQueryOrderResponse;
import com.freemud.application.sdk.api.storecenter.service.StoreCenterService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: ParkingOrderServiceImpl
 * @Package cn.freemud.service.impl
 * @Description:
 * @author: ping1.wu
 * @date: 2020/7/3 15:37
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
@Service
public class ParkingOrderServiceImpl implements ParkingOrderService {

    @Autowired
    private OrderDownLoadSdkService orderDownLoadSdkService;
    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;

    @Override
    public BaseResponse queryOrders(QueryParkingOrderVo requestVo) {
        QueryParkingOrdersResponseVo responseVo = new QueryParkingOrdersResponseVo();
        String trackingNo = LogThreadLocal.getTrackingNo();
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(requestVo.getSessionId());
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        OrderConditionsReq request = new OrderConditionsReq();
        request.setUserId(userInfo.getMemberId());
        request.setPartnerId(userInfo.getPartnerId());
        request.setPageSize(requestVo.getPageSize());
        request.setPageNum(requestVo.getPageNumber());
        Date date = new Date();
        request.setStartTimestamp(DateUtil.addMonths(date, -3).getTime()/1000);
        request.setEndTimestamp(date.getTime()/1000);
        request.setOrderClients(Arrays.asList(OrderClientType.PARKING.getIndex()));
        request.setPayStatuses(Arrays.asList(2));
        request.setBizTypes(Arrays.asList(1,99));
        BaseDownLoadResponse<List<OrderInfoReqs>> listBaseDownLoadResponse = orderDownLoadSdkService.queryOrderByConditions(request, trackingNo);
        if(listBaseDownLoadResponse == null && !ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(listBaseDownLoadResponse.getCode())){
            return ResponseUtil.success();
        }
        List<ParkingOrderResponseVo> dates = new ArrayList<>();
        for (OrderInfoReqs orderInfo : listBaseDownLoadResponse.getResult()){
            dates.add(convent2QueryOrdersDto(orderInfo));
        }
        responseVo.setDates(dates);
        responseVo.setCount(listBaseDownLoadResponse.getTotalNum());
        return ResponseUtil.success(responseVo);
    }

    @Override
    public BaseResponse queryOrderById(QueryParkingOrderVo requestVo) {
        String trackingNo = LogThreadLocal.getTrackingNo();
        AssortmentCustomerInfoVo userInfo = customerInfoManager.getCustomerInfoByObject(requestVo.getSessionId());
        if (userInfo == null || StringUtils.isEmpty(userInfo.getMemberId())) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        QueryByCodeResponse queryByCodeResponse = orderDownLoadSdkService.queryOrderByCode(userInfo.getPartnerId(), requestVo.getOrderCode(), trackingNo);
        if (null == queryByCodeResponse || !ResponseCodeConstant.RESPONSE_SUCCESS_STR.equals(queryByCodeResponse.getCode())) {
            return ResponseUtil.success();
        }
        ParkingOrderResponseVo responseVo = convent2QueryOrdersDto(queryByCodeResponse.getResult());
        return ResponseUtil.success(responseVo);
    }


    private ParkingOrderResponseVo convent2QueryOrdersDto(OrderInfoReqs orderInfoReqs){
        if(orderInfoReqs == null || orderInfoReqs.getOrderCode() == null){
            return null;
        }
        ParkingOrderResponseVo respVo = new ParkingOrderResponseVo();
        respVo.setOrderCode(orderInfoReqs.getOrderCode());
        if(StringUtils.isNotBlank(orderInfoReqs.getExtInfo()) && orderInfoReqs.getPayTime() != null){
            OrderExtInfoDto extInfoDto = JSONObject.parseObject(orderInfoReqs.getExtInfo(), OrderExtInfoDto.class);
            respVo.setParkingAreaId(extInfoDto.getParkingAreaId());
            respVo.setParkingAreaName(extInfoDto.getParkingAreaName());
            respVo.setCarNumber(extInfoDto.getCarNumber());
            Long diffMinute = (Long.parseLong(orderInfoReqs.getPayTime()) - Long.parseLong(extInfoDto.getInTime()))/1000/60;
            respVo.setParkingTime(diffMinute.toString());
            respVo.setInTime(DateUtil.convert2Str(new Date(Long.parseLong(extInfoDto.getInTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
            respVo.setOutTime(DateUtil.convert2Str(new Date(Long.parseLong(orderInfoReqs.getPayTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        }
        Long discountAmount = 0L;
        if (CollectionUtils.isNotEmpty(orderInfoReqs.getOrderSettlementDetailList())) {
            for (OrderSettlementResp orderSettlementResp : orderInfoReqs.getOrderSettlementDetailList()) {
                discountAmount += orderSettlementResp.getShopDiscountAmount();
            }
        }
        respVo.setDiscountAmount(discountAmount.intValue());
        respVo.setActualPayAmount(orderInfoReqs.getActualPayAmount().intValue());
        respVo.setGmtCreate(DateUtil.convert2Str(new Date(Long.parseLong(orderInfoReqs.getCreateTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        respVo.setGmtPay(DateUtil.convert2Str(orderInfoReqs.getPayTime() == null ? null : new Date(Long.parseLong(orderInfoReqs.getPayTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        respVo.setOriginalAmount(orderInfoReqs.getOriginalAmount().intValue());

        respVo.setPayChannel(orderInfoReqs.getPayChannel());
        respVo.setPayChannelType(orderInfoReqs.getPayChannelType());
        return respVo;
    }


}
