package cn.freemud.service.impl;

import cn.freemud.adapter.CollageOrderAdapter;
import cn.freemud.base.entity.BaseResponse;
import cn.freemud.entities.vo.CollageOrderRequestVo;
import cn.freemud.entities.vo.CollageOrderResponseVo;
import cn.freemud.enums.ResponseResult;
import cn.freemud.interceptor.ServiceException;
import cn.freemud.service.CollageOrderService;
import cn.freemud.utils.ResponseUtil;
import com.freemud.sdk.api.assortment.shoppingcart.domain.CollageOrder;
import com.freemud.sdk.api.assortment.shoppingcart.domain.CollageOrderDto;
import com.freemud.sdk.api.assortment.shoppingcart.service.impl.CollageOrderBaseServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Optional;

/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @version V1.0
 * @Title: null.java
 * @Package
 * @Description: (用一句话描述该文件做什么)
 * @author: pegnfei.liu
 * @date: 2020-9-24
 * @Copyright: 2020 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目的
 */

@Service
public class CollageOrderServiceImpl implements CollageOrderService {
    @Autowired
    private CollageOrderAdapter collageOrderAdapter;
    @Autowired
    private CollageOrderBaseServiceImpl collageOrderBaseService;
    @Autowired
    private ShoppingCartCollageServiceImpl shoppingCartCollageService;


    /**
     * 查询拼单订单信息（拼单基础信息 拼单参与人列表）
     * @param request(partnerId shopId userId)
     * @return
     */
    @Override
    public BaseResponse queryCollageOrder(CollageOrderRequestVo request) {
        CollageOrderDto collageOrderDto = this.collageOrderAdapter.convert2CollageOrderDto(request);
        // 查询时需传入拼单创建人的userId，若上送字段为空时，默认查询当前登录人自己的拼单信息
        if (StringUtils.isEmpty(request.getCreateCollageUserId())) {
            collageOrderDto.setCreateCollageUserId(this.getUserIdBySessionId(request.getSessionId()));
        }
        BaseResponse<CollageOrder> queryCollageOrderResponse = this.collageOrderBaseService.queryCollageOrder(collageOrderDto);
        CollageOrder collageOrder = queryCollageOrderResponse.getResult();

        // SDK查询订单返回非成功code或返回结果订单信息为空时，返回前端异常信息
        Optional.ofNullable(queryCollageOrderResponse).filter(resp -> (ResponseResult.SUCCESS.getCode().equals(resp.getCode()) && !ObjectUtils.isEmpty(collageOrder))).orElseThrow(() -> new ServiceException(ResponseResult.COLLAGE_NOT_EXIST));

        CollageOrderResponseVo collageOrderResponseVo = new CollageOrderResponseVo();
        // 订单基础信息
        collageOrderResponseVo.setOrder(collageOrder);
        // 订单锁定状态
        collageOrderResponseVo.setLocked(this.collageOrderBaseService.isLockedCollageOrder(collageOrderDto).getResult());
        // TODO 订单参与人列表信息

        return ResponseUtil.success(collageOrderResponseVo);
    }

    /**
     * 创建拼单订单基础信息
     * @param request(partnerId shopId sessionId)
     * @return
     */
    @Override
    public BaseResponse createCollageOrder(CollageOrderRequestVo request) {
        CollageOrderDto collageOrderDto = this.collageOrderAdapter.convert2CollageOrderDto(request);
        // 根据sessionId查询对应登录用户信息
        collageOrderDto.setCreateCollageUserId(this.getUserIdBySessionId(request.getSessionId()));

        // 创建拼单订单基础缓存信息
        BaseResponse<CollageOrder> createCollageOrderResponse = this.collageOrderBaseService.createCollageOrder(collageOrderDto);

        // SDK创建订单返回非成功code时，返回前端异常信息
        Optional.ofNullable(createCollageOrderResponse).filter(resp -> ResponseResult.SUCCESS.getCode().equals(resp.getCode())).orElseThrow(() -> new ServiceException(ResponseResult.COLLAGE_ALREADY_EXIST));

        CollageOrderResponseVo collageOrderResponseVo = new CollageOrderResponseVo();
        collageOrderResponseVo.setOrder(createCollageOrderResponse.getResult());
        return ResponseUtil.success(collageOrderResponseVo);
    }

    /**
     * 取消拼单订单，删除相关缓存信息
     * @param request
     * @return
     */
    @Override
    public BaseResponse cancelCollageOrder(CollageOrderRequestVo request) {
        CollageOrderDto collageOrderDto = this.collageOrderAdapter.convert2CollageOrderDto(request);
        // 根据sessionId查询对应登录用户信息
        collageOrderDto.setCreateCollageUserId(this.getUserIdBySessionId(request.getSessionId()));
        this.checkCollageOrderOwner(collageOrderDto);
        return this.collageOrderBaseService.cancelCollageOrder(collageOrderDto);
    }

    /**
     * 锁定拼单订单
     * @param request
     * @return
     */
    @Override
    public BaseResponse lockCollageOrder(CollageOrderRequestVo request) {
        CollageOrderDto collageOrderDto = this.collageOrderAdapter.convert2CollageOrderDto(request);
        // 根据sessionId查询对应登录用户信息
        collageOrderDto.setCreateCollageUserId(this.getUserIdBySessionId(request.getSessionId()));
        this.checkCollageOrderOwner(collageOrderDto);
        return this.collageOrderBaseService.lockCollageOrder(collageOrderDto);
    }

    /**
     * 解锁拼单订单
     * @param request
     * @return
     */
    @Override
    public BaseResponse unlockCollageOrder(CollageOrderRequestVo request) {
        CollageOrderDto collageOrderDto = this.collageOrderAdapter.convert2CollageOrderDto(request);
        // 根据sessionId查询对应登录用户信息
        collageOrderDto.setCreateCollageUserId(this.getUserIdBySessionId(request.getSessionId()));
        this.checkCollageOrderOwner(collageOrderDto);
        return this.collageOrderBaseService.unlockCollageOrder(collageOrderDto);
    }

    /**
     * 根据sessionId查询登录用户的userId
     * @param sessionId
     * @return
     */
    private String getUserIdBySessionId(String sessionId) {
        return this.shoppingCartCollageService.getCustomerInfoVo(sessionId).getMemberId();
    }

    /**
     * 查询当前拼单订单基础信息是否存在
     * @param collageOrderDto
     * @return
     */
    private Boolean isCollageOrderExist(CollageOrderDto collageOrderDto) {
        // 查询当前拼单订单基础信息是否存在
        return ObjectUtils.isEmpty(this.collageOrderBaseService.queryCollageOrder(collageOrderDto).getResult()) ? false : true;
    }

    /**
     * 拼单订单检查
     * @param collageOrderDto
     */
    private void checkCollageOrderOwner(CollageOrderDto collageOrderDto) {
        CollageOrder collageOrder = this.collageOrderBaseService.queryCollageOrder(collageOrderDto).getResult();
        // 拼单订单信息不存在时，返回错误提示
        Optional.ofNullable(collageOrder).orElseThrow(() -> new ServiceException(ResponseResult.COLLAGE_NOT_EXIST));
        // 若当前操作人并非拼单邀请人时，返回错误提示 当前用户不是拼单发起人，无法操作
        Optional.ofNullable(collageOrder).map(CollageOrder::getCreateCollageUserId).filter(userId -> userId.equals(collageOrderDto.getCreateCollageUserId())).orElseThrow(() -> new ServiceException(ResponseResult.COLLAGE_NOT_OWNER));
    }
}
