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.AddProductEvaluationReqDto;
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.interceptor.ServiceException;
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.db.AssortmentOrderEvaluation;
import com.freemud.api.assortment.datamanager.entity.db.AssortmentProductEvaluation;
import com.freemud.api.assortment.datamanager.entity.dto.InsertOrderEvaluationReqDto;
import com.freemud.api.assortment.datamanager.entity.dto.InsertProductEvaluationReqDto;
import com.freemud.api.assortment.datamanager.entity.vo.GetEvaluationDetailByOrderIdRepVo;
import com.freemud.api.assortment.datamanager.manager.AssortmentEvaluationManager;
import com.freemud.application.sdk.api.log.ErrorLog;
import com.freemud.application.sdk.api.ordercenter.entities.v1.OrderBeanV1;
import com.freemud.sdk.api.assortment.order.request.order.BaseQueryOrderRequest;
import com.freemud.sdk.api.assortment.order.response.order.OrderDetailResponse;
import com.freemud.sdk.api.assortment.order.service.OrderCenterSdkService;
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.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 OrderCenterSdkService orderCenterSdkService;
    @Autowired
    private AssortmentEvaluationManager assortmentEvaluationManager;
    @Autowired
    private EvaluationAdapter evaluationAdapter;
    @Autowired
    private ActivityApplicationClient activityApplicationClient;

    @Override
    public BaseResponse userOrderEvaluationNew(AddUserOrderEvaluationNewRequestVo request) {
        OrderEvaluationStatus orderEvaluationStatus = new OrderEvaluationStatus(EvaluationStatus.SUCCESS.getCode());
        try {
            BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
            baseQueryOrderRequest.setOrderId(request.getOrderId());
            OrderDetailResponse orderDetailResponse = orderCenterSdkService.getByIdForParentProduct(baseQueryOrderRequest);
            if (orderDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(orderDetailResponse.getErrcode() + "") || orderDetailResponse.getData() == null) {
                return ResponseUtil.success(ResponseResult.ORDER_NOT_EXIST);
            }
            OrderBeanV1 order = orderDetailResponse.getData();

            // 判断订单是否评价
            List<AssortmentOrderEvaluation> orderEvaluationDetails = assortmentEvaluationManager.getOrderEvaluationDetailsByOrderId(request.getOrderId());
            if (CollectionUtils.isNotEmpty(orderEvaluationDetails)) {
                // 已经评价 查询是否有活动数据
                AssortmentOrderEvaluation assortmentOrderEvaluation = orderEvaluationDetails.get(0);
                orderEvaluationStatus.setStatus(EvaluationStatus.REPEAT.getCode());
                CheckAndJoinResponse checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getData(), request.getSessionId(), request.getOrderId(), assortmentOrderEvaluation.getActivityId());
                orderEvaluationStatus.setResult(checkAndJoinMsg);
                return ResponseUtil.success(orderEvaluationStatus);
            }
            // 添加订单评价信息
            InsertOrderEvaluationReqDto insertOrderEvaluationReqDto = evaluationAdapter.convent2InsertOrderEvaluationReqDto(request, order);
            // fisherman  有评价有礼数据 就设置到对象中
            CheckAndJoinResponse checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getData(), request.getSessionId(), request.getOrderId(), null);
            orderEvaluationStatus.setResult(checkAndJoinMsg);
            if (checkAndJoinMsg !=null) {
                insertOrderEvaluationReqDto.setActivityId(checkAndJoinMsg.getActivityId());
            }
            assortmentEvaluationManager.insertOrderEvaluationDetails(insertOrderEvaluationReqDto);
            // 添加订单下的商品评价信息
            List<AddProductEvaluationReqDto> addProductEvaluationList = request.getProductEvaluationList();
            if (CollectionUtils.isNotEmpty(addProductEvaluationList)) {
                for (AddProductEvaluationReqDto addProductEvaluationReqDto : addProductEvaluationList) {
                    InsertProductEvaluationReqDto insertProductEvaluationReqDto = evaluationAdapter.convent2InsertProductEvaluationReqDto(request, addProductEvaluationReqDto);
                    assortmentEvaluationManager.insertProductEvaluation(insertProductEvaluationReqDto);
                }
            }
        } 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 data
     * @param sessionId
     * @param orderId
     * @param activityId
     * @return
     */
    private CheckAndJoinResponse getCheckAndJoinMsg(OrderBeanV1 data,
                                                    String sessionId,
                                                    String orderId,
                                                    String activityId) {
        // 老小程序 没有sessionId 不需要查询评价有礼
        if (sessionId == null) {
            return null;
        }
        if (StringUtils.isEmpty(activityId)) {
            activityId =null;
        }
        CheckAndJoinRequest requestCommon = getCheckAndJoinRequest(data, sessionId, orderId, activityId);
        BaseResponse<CheckAndJoinResponse> checkAndJoin = activityApplicationClient.checkAndJoin(requestCommon);
//        LogUtil.info("请求活动-评价有礼",requestCommon, checkAndJoin);
        if (checkAndJoin != null
                && checkAndJoin.getCode().equals(ResponseResult.SUCCESS.getCode())) {
            return checkAndJoin.getResult();
        }
        return null;
    }

    private CheckAndJoinRequest getCheckAndJoinRequest(OrderBeanV1 data,
                                                       String sessionId,
                                                       String orderId,
                                                       String activityId) {
        CheckAndJoinRequest requestCommon = new CheckAndJoinRequest();
        requestCommon.setOid(orderId);
        requestCommon.setSessionId(sessionId);
        requestCommon.setStoreId(data.getShopId());
        requestCommon.setOrderCreateTime(DateUtil.convert2Str(new Date(data.getGmtCreate()), DateUtil.FORMAT_YYYY_MM_DD_HHMMSS));
        requestCommon.setActivityId(activityId);
        return requestCommon;

    }

    @Override
    public BaseResponse getEvaluationByOrderId(GetEvaluationDetailByOrderIdRequestVo request) {
        if (StringUtils.isEmpty(request.getOrder_id())) {
            return ResponseUtil.success();
        }
        /**
         * 根据order_id 查询订单评价详情
         */
        List<AssortmentOrderEvaluation> orderEvaluationListAmount = assortmentEvaluationManager.getOrderEvaluationDetailsByOrderId(request.getOrder_id());
        if (orderEvaluationListAmount != null && orderEvaluationListAmount.size() > 0) {
            /**
             * 查询对应订单的商品详情
             */
            List<GetEvaluationDetailByOrderIdRepVo> getEvaluationDetailByOrderIdList = new ArrayList<>();
            for (AssortmentOrderEvaluation orderEvaluation : orderEvaluationListAmount) {
                GetEvaluationDetailByOrderIdRepVo getEvaluationDetailByOrderIdRepVo = new GetEvaluationDetailByOrderIdRepVo();
                List<AssortmentProductEvaluation> productEvaluationList = assortmentEvaluationManager.getProductEvalutionDetailsByOrderIds(Arrays.asList(orderEvaluation.getOrderId()));
                List<GetEvaluationDetailByOrderIdRepVo.ProductListVo> productList = new ArrayList<>();
                if (productEvaluationList != null && productEvaluationList.size() > 0) {
                    for (AssortmentProductEvaluation productEvaluation : productEvaluationList) {
                        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 getEvaluationStatus(GetEvaluationDetailByOrderIdRequestVo request) {
        List<AssortmentOrderEvaluation> orderEvaluationListAmount = assortmentEvaluationManager.getOrderEvaluationDetailsByOrderId(request.getOrder_id());
        if (orderEvaluationListAmount != null && orderEvaluationListAmount.size() > 0) {
            return ResponseUtil.success(new OrderEvaluationStatus(1));
        } else {
            return ResponseUtil.success(new OrderEvaluationStatus(2));
        }
    }

    @Override
    public BaseResponse getEvaluationStatusNew(GetEvaluationStatusNewRequestVo request) {
        if (StringUtils.isEmpty(request.getOrderId())) {
            return ResponseUtil.success(new OrderEvaluationStatus(2));
        }
        BaseQueryOrderRequest baseQueryOrderRequest = new BaseQueryOrderRequest();
        baseQueryOrderRequest.setOrderId(request.getOrderId());
        OrderDetailResponse orderDetailResponse = orderCenterSdkService.getByIdForParentProduct(baseQueryOrderRequest);
        if (orderDetailResponse == null || !ResponseResult.SUCCESS.getCode().equals(orderDetailResponse.getErrcode() + "") || orderDetailResponse.getData() == null) {
            throw new ServiceException(ResponseResult.ORDER_NOT_EXIST);
        }

        OrderEvaluationStatus orderEvaluationStatus = new OrderEvaluationStatus(1);
        List<AssortmentOrderEvaluation> orderEvaluationListAmount = assortmentEvaluationManager.getOrderEvaluationDetailsByOrderId(request.getOrderId());
        CheckAndJoinResponse checkAndJoinMsg;
        if (orderEvaluationListAmount != null && orderEvaluationListAmount.size() > 0) {
            // 获取 评价有礼活动
            AssortmentOrderEvaluation assortmentOrderEvaluation = orderEvaluationListAmount.get(0);
            checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getData(), request.getSessionId(), assortmentOrderEvaluation.getOrderId(), assortmentOrderEvaluation.getActivityId());
        } else {
            orderEvaluationStatus.setStatus(2);
            checkAndJoinMsg = getCheckAndJoinMsg(orderDetailResponse.getData(), request.getSessionId(), request.getOrderId(), null);
        }
        orderEvaluationStatus.setResult(checkAndJoinMsg);
        return ResponseUtil.success(orderEvaluationStatus);
    }

}
