package cn.freemud.service.impl;

import cn.freemud.adapter.EvaluationAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.base.util.DateUtil;
import cn.freemud.entities.dto.Evaluation.OrderEvaluationStatus;
import cn.freemud.entities.dto.activity.CheckAndJoinRequest;
import cn.freemud.entities.dto.activity.CheckAndJoinResponse;
import cn.freemud.entities.vo.AddUserOrderEvaluationNewRequestVo;
import cn.freemud.entities.vo.GetEvaluationDetailByOrderIdRequestVo;
import cn.freemud.entities.vo.GetEvaluationStatusNewRequestVo;
import cn.freemud.enums.EvaluationStatus;
import cn.freemud.enums.ResponseResult;
import cn.freemud.service.EvaluationService;
import cn.freemud.service.thirdparty.ActivityApplicationClient;
import cn.freemud.utils.ResponseUtil;
import com.alibaba.fastjson.JSON;
import com.freemud.api.assortment.datamanager.entity.vo.GetEvaluationDetailByOrderIdRepVo;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.log.LogThreadLocal;
import com.freemud.application.sdk.api.ordercenter.request.evaluation.*;
import com.freemud.application.sdk.api.ordercenter.response.OrderBaseResp;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.QueryByCodeResponse;
import com.freemud.application.sdk.api.ordercenter.service.OrderSdkService;
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.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By www.freemud.com
 *
 * @version V1.0
 * @Title:
 * @Package: cn.freemud.service.impl
 * @Descripttion:
 * @author: shuhu.hou
 * @date: 2019/8/12
 * @Copyright: 2017 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目.
 */
@Service
public class EvaluationServiceImpl implements EvaluationService {

    @Autowired
    private OrderSdkService orderSdkService;
    @Autowired
    private EvaluationAdapter evaluationAdapter;
    @Autowired
    private ActivityApplicationClient activityApplicationClient;

    @Override
    public BaseResponse userOrderEvaluationNew(AddUserOrderEvaluationNewRequestVo request) {
        OrderEvaluationStatus orderEvaluationStatus = new OrderEvaluationStatus(EvaluationStatus.SUCCESS.getCode());
        try {
            QueryByCodeResponse orderDetailResponse = orderSdkService.getOrderInfo("", request.getOrderId(), "", null, LogThreadLocal.getTrackingNo(),request.getPartnerId());
            if (orderDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(orderDetailResponse.getCode() + "") || orderDetailResponse.getResult() == null) {
                return ResponseUtil.error(ResponseResult.ORDER_NOT_EXIST);
            }
            OrderInfoReqs orderInfo = orderDetailResponse.getResult();

            // 判断订单是否评价
            GetEvaluationsByOrderIdReq getEvaluationsByOrderIdReq = new GetEvaluationsByOrderIdReq();
            getEvaluationsByOrderIdReq.setOrderId(request.getOrderId());
            getEvaluationsByOrderIdReq.setPartnerId(request.getPartnerId());
            OrderBaseResp<GetEvaluationsByOrderIdResultDto> evaluationsByOrderId = orderSdkService.getEvaluationsByOrderId(getEvaluationsByOrderIdReq, LogThreadLocal.getTrackingNo());
            List<GetOrderEvaluationDto> orderEvaluationDetails = evaluationsByOrderId.getResult().getOrderEvaluations();
            if (CollectionUtils.isNotEmpty(orderEvaluationDetails)) {
                // 已经评价 查询是否有活动数据
                GetOrderEvaluationDto assortmentOrderEvaluation = orderEvaluationDetails.get(0);
                orderEvaluationStatus.setStatus(EvaluationStatus.REPEAT.getCode());
                CheckAndJoinResponse checkAndJoinMsg = getCheckAndJoinMsg(orderInfo, request.getSessionId(), request.getOrderId(), assortmentOrderEvaluation.getActivityId());
                orderEvaluationStatus.setResult(checkAndJoinMsg);
                return ResponseUtil.success(orderEvaluationStatus);
            }

            // 添加订单评价信息
            AddEvaluationReq requestDto = evaluationAdapter.convent2InsertOrderEvaluationReqDto(request, orderInfo);
            // fisherman  有评价有礼数据 就设置到对象中
            CheckAndJoinResponse checkAndJoinMsg = getCheckAndJoinMsg(orderInfo, request.getSessionId(), request.getOrderId(), null);
            orderEvaluationStatus.setResult(checkAndJoinMsg);
            if (checkAndJoinMsg !=null) {
                requestDto.setActivityId(checkAndJoinMsg.getActivityId());
            }
            orderSdkService.addEvaluation(requestDto, LogThreadLocal.getTrackingNo());
        } catch (Exception ex) {
            ErrorLog.errorConvertJson(this.getClass(), "userOrderEvaluationNewError /order/userOrderEvaluationNew" + JSON.toJSONString(request), ex);
            return ResponseUtil.success(new OrderEvaluationStatus(EvaluationStatus.FAIL.getCode()));
        }
        return ResponseUtil.success(orderEvaluationStatus);
    }

    /**
     * 获取活动数据 用于校验
     *
     * @param sessionId
     * @param orderId
     * @param activityId
     * @return
     */
    private CheckAndJoinResponse getCheckAndJoinMsg(OrderInfoReqs orderInfo,
                                                    String sessionId,
                                                    String orderId,
                                                    String activityId) {
        // 老小程序 没有sessionId 不需要查询评价有礼
        if (sessionId == null) {
            return null;
        }
        if (StringUtils.isEmpty(activityId)) {
            activityId =null;
        }
        CheckAndJoinRequest requestCommon = new CheckAndJoinRequest();
        requestCommon.setOid(orderId);
        requestCommon.setSessionId(sessionId);
        requestCommon.setStoreId(orderInfo.getStoreId());
        requestCommon.setOrderCreateTime(DateUtil.convert2Str(new Date(Long.parseLong(orderInfo.getCreateTime())), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        requestCommon.setActivityId(activityId);
        BaseResponse<CheckAndJoinResponse> checkAndJoin = activityApplicationClient.checkAndJoin(requestCommon);
        if (checkAndJoin != null && checkAndJoin.getCode().equals(ResponseResult.SUCCESS.getCode())) {
            return checkAndJoin.getResult();
        }
        return null;
    }


    @Override
    public BaseResponse getEvaluationByOrderId(GetEvaluationDetailByOrderIdRequestVo request) {
        if (StringUtils.isEmpty(request.getOrder_id())) {
            return ResponseUtil.success();
        }
        /**
         * 根据order_id 查询订单评价详情
         */
        GetEvaluationsByOrderIdReq getEvaluationsByOrderIdReq = new GetEvaluationsByOrderIdReq();
        getEvaluationsByOrderIdReq.setOrderId(request.getOrder_id());
        getEvaluationsByOrderIdReq.setPartnerId(request.getPartnerId());
        OrderBaseResp<GetEvaluationsByOrderIdResultDto> evaluationsByOrderId = orderSdkService.getEvaluationsByOrderId(getEvaluationsByOrderIdReq, LogThreadLocal.getTrackingNo());

        if(evaluationsByOrderId == null || evaluationsByOrderId.getResult() == null || evaluationsByOrderId.getResult().getOrderEvaluations() == null){
            return ResponseUtil.success();
        }
        if (evaluationsByOrderId.getResult().getOrderEvaluations().size() > 0) {
            /**
             * 查询对应订单的商品详情
             */
            List<GetEvaluationDetailByOrderIdRepVo> getEvaluationDetailByOrderIdList = new ArrayList<>();
            for (GetOrderEvaluationDto orderEvaluation : evaluationsByOrderId.getResult().getOrderEvaluations()) {
                GetEvaluationDetailByOrderIdRepVo getEvaluationDetailByOrderIdRepVo = new GetEvaluationDetailByOrderIdRepVo();
                List<GetEvaluationDetailByOrderIdRepVo.ProductListVo> productList = new ArrayList<>();
                if (orderEvaluation.getProductEvaluationList() != null && orderEvaluation.getProductEvaluationList().size() > 0) {
                    for (GetProductEvaluationDto productEvaluation : orderEvaluation.getProductEvaluationList()) {
                        GetEvaluationDetailByOrderIdRepVo.ProductListVo productListVo = new GetEvaluationDetailByOrderIdRepVo.ProductListVo();
                        productListVo.setIs_call(productEvaluation.getIsCall());
                        productListVo.setProduct_name(productEvaluation.getProductName());
                        productList.add(productListVo);
                    }
                }
                getEvaluationDetailByOrderIdRepVo.setCustomer_name(orderEvaluation.getCustomerName());
                getEvaluationDetailByOrderIdRepVo.setCustomer_mobile(orderEvaluation.getCustomerMobile());
                getEvaluationDetailByOrderIdRepVo.setStore_name(orderEvaluation.getStoreName());
                getEvaluationDetailByOrderIdRepVo.setCreate_time(DateUtil.convert2String(orderEvaluation.getCreateTime(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                getEvaluationDetailByOrderIdRepVo.setDelivery_speed(orderEvaluation.getDeliverySpeed());
                getEvaluationDetailByOrderIdRepVo.setHealth(orderEvaluation.getHealth());
                getEvaluationDetailByOrderIdRepVo.setTaste(orderEvaluation.getTaste());
                getEvaluationDetailByOrderIdRepVo.setSurroundings(orderEvaluation.getSurroundings());
                getEvaluationDetailByOrderIdRepVo.setService(orderEvaluation.getService());
                getEvaluationDetailByOrderIdRepVo.setEvaluation_content(orderEvaluation.getEvaluationContent());
                getEvaluationDetailByOrderIdRepVo.setOrder_id(orderEvaluation.getOrderId());
                getEvaluationDetailByOrderIdRepVo.setOrder_type(orderEvaluation.getOrderType());
                getEvaluationDetailByOrderIdRepVo.setCreate_order_time(DateUtil.convert2String(orderEvaluation.getCreateOrderTime(), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
                getEvaluationDetailByOrderIdRepVo.setProduct_evaluation_list(productList);
                getEvaluationDetailByOrderIdList.add(getEvaluationDetailByOrderIdRepVo);
            }
            return ResponseUtil.success(getEvaluationDetailByOrderIdList.get(0));
        }
        return ResponseUtil.success();
    }

    @Override
    public BaseResponse getEvaluationStatusNew(GetEvaluationStatusNewRequestVo request) {
        if (StringUtils.isEmpty(request.getOrderId())) {
            return ResponseUtil.success(new OrderEvaluationStatus(2));
        }

        QueryByCodeResponse orderDetailResponse = orderSdkService.getOrderInfo("", request.getOrderId(), "", null, LogThreadLocal.getTrackingNo(),request.getPartnerId());
        if (orderDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(orderDetailResponse.getCode() + "")
                || orderDetailResponse.getResult() == null || StringUtils.isEmpty(orderDetailResponse.getResult().getOrderCode())) {
            return ResponseUtil.success(ResponseResult.ORDER_NOT_EXIST);
        }

        OrderEvaluationStatus orderEvaluationStatus = new OrderEvaluationStatus(1);

        GetEvaluationsByOrderIdReq getEvaluationsByOrderIdReq = new GetEvaluationsByOrderIdReq();
        getEvaluationsByOrderIdReq.setOrderId(request.getOrderId());
        getEvaluationsByOrderIdReq.setPartnerId(request.getPartnerId());
        OrderBaseResp<GetEvaluationsByOrderIdResultDto> evaluationsByOrderId = orderSdkService.getEvaluationsByOrderId(getEvaluationsByOrderIdReq, LogThreadLocal.getTrackingNo());
        CheckAndJoinResponse checkAndJoinMsg;
        if (evaluationsByOrderId != null && evaluationsByOrderId.getResult() != null && CollectionUtils.isNotEmpty(evaluationsByOrderId.getResult().getOrderEvaluations())) {
            // 获取 评价有礼活动
            GetOrderEvaluationDto assortmentOrderEvaluation = evaluationsByOrderId.getResult().getOrderEvaluations().get(0);
            checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getResult(), request.getSessionId(), assortmentOrderEvaluation.getOrderId(), assortmentOrderEvaluation.getActivityId());
        } else {
            orderEvaluationStatus.setStatus(2);
            checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getResult(), request.getSessionId(), request.getOrderId(), null);
        }
        orderEvaluationStatus.setResult(checkAndJoinMsg);
        return ResponseUtil.success(orderEvaluationStatus);
    }

}
