/**
 * All rights Reserved, Designed By www.freemud.cn
 *
 * @Title: ShoppingCart
 * @Package cn.freemud.controller
 * @Description:
 * @author: ping.wu
 * @date: 2018/5/18 18:07
 * @version V1.0
 * @Copyright: 2018 www.freemud.cn Inc. All rights reserved.
 * 注意：本内容仅限于上海非码科技内部传阅，禁止外泄以及用于其他的商业目
 */
package cn.freemud.demo.controller;

import cn.freemud.base.entity.BaseResponse;
import cn.freemud.demo.adapter.service.*;
import cn.freemud.demo.entities.AddGoodsShoppingCartBO;
import cn.freemud.demo.entities.ListCartGoodsRequestDTO;
import cn.freemud.demo.entities.ShoppingCartGoodsBO;
import cn.freemud.demo.entities.UpdateGoodsQtyRequestDTO;
import cn.freemud.demo.entities.bo.goods.add.BaseAddGoodsBO;
import cn.freemud.demo.entities.bo.goods.list.ListCartGoodsBO;
import cn.freemud.demo.entities.bo.goods.update.UpdateAddGoodsBO;
import cn.freemud.demo.entities.bo.goods.update.UpdateAddGoodsVO;
import cn.freemud.demo.entities.dto.goods.add.BaseAddGoodsVO;
import cn.freemud.demo.entities.dto.goods.add.AddGoodsRequestDTO;
import cn.freemud.demo.entities.dto.goods.add.list.BaseListCartGoodsVO;
import cn.freemud.demo.entities.dto.goods.add.update.BaseUpdateGoodsQtyVO;
import cn.freemud.demo.enums.BizTypeEnum;
import cn.freemud.demo.factory.ServiceFactory;
import cn.freemud.demo.service.AbstractAddGoodsService;
import cn.freemud.demo.service.AbstractListCartGoodsService;
import cn.freemud.demo.service.AbstractUpdateGoodsQtyService;
import cn.freemud.demo.utils.BizTypeUtil;
import cn.freemud.entities.dto.GetMemberInfoRequestDto;
import cn.freemud.entities.vo.*;
import cn.freemud.enums.OrderChannelType;
import cn.freemud.enums.ResponseResult;
import cn.freemud.service.ShoppingCartNewService;
import cn.freemud.service.impl.ShoppingCartMallServiceImpl;
import cn.freemud.service.impl.ShoppingCartMealServiceImpl;
import cn.freemud.service.impl.ShoppingCartNewServiceImpl;
import cn.freemud.service.impl.ShoppingCartToolsServiceImpl;
import cn.freemud.utils.ResponseUtil;
import com.freemud.api.assortment.datamanager.entity.vo.AssortmentCustomerInfoVo;
import com.freemud.api.assortment.datamanager.enums.IappIdType;
import com.freemud.api.assortment.datamanager.manager.customer.AssortmentCustomerInfoManager;
import com.freemud.application.sdk.api.base.SDKCommonBaseContextWare;
import com.freemud.application.sdk.api.log.ApiAnnotation;
import com.freemud.application.sdk.api.log.LogParams;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@RestController
@RequestMapping(value = "/shoppingCart/demo", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(value = "购物车 controller", tags = {"购物车管理接口"})
@Slf4j
public class ShoppingCartDemoController {

    @Autowired
    private AssortmentCustomerInfoManager customerInfoManager;

    @Autowired
    private AddGoodsBOAdapter addGoodsBOAdapter;

    @Autowired
    private AddGoodsVOAdapter addGoodsVOAdapter;

    @Autowired
    private UpdateGoodsQtyBOAdapter updateGoodsQtyBOAdapter;

    @Autowired
    private UpdateGoodsQtyVOAdapter updateGoodsQtyVOAdapter;

    @Autowired
    private ListCartGoodsBOAdapter listCartGoodsBOAdapter;

    @Autowired
    private ListCartGoodsVOAdapter listCartGoodsVOAdapter;


    /**
     * 向购物车中添加商品
     */
    @ApiAnnotation(logMessage = "addGoods")
    @PostMapping(value = "/addGoods")
    public BaseResponse addGoods(@LogParams @RequestBody Map<String, Object> request) {

        AddGoodsRequestDTO baseRequestDTO = new AddGoodsRequestDTO();
        try {
            BeanUtils.populate(baseRequestDTO, request);
        } catch (Exception exception){
            return ResponseUtil.error("");
        }

        /**
         * 是否用新字段,还是沿用老逻辑
         */
        BizTypeEnum bizType = BizTypeUtil.getBizType(baseRequestDTO.getPartnerId());

        AbstractAddGoodsService addGoodsServiceInstance = ServiceFactory.createAddGoodsServiceInstance(bizType.getCode());

        BaseAddGoodsBO addGoodsBOInstance = addGoodsBOAdapter.convert2AddGoodsBO(bizType.getCode(), baseRequestDTO);
        ShoppingCartGoodsBO addGoodsResponseBO = addGoodsServiceInstance.addGoods(addGoodsBOInstance);
        BaseAddGoodsVO baseAddGoodsVO = addGoodsVOAdapter.convert2AddGoodsVO(bizType.getCode(), addGoodsResponseBO);

        return ResponseUtil.success(baseAddGoodsVO);

    }

    /**
     * 修改购物车中商品数量
     */
    @ApiAnnotation(logMessage = "updateGoodsQty")
    @PostMapping(value = "/updateGoodsQty")
    public BaseResponse updateGoodsQty(@LogParams @RequestBody Map<String, Object> request) {

        UpdateGoodsQtyRequestDTO baseRequestDTO = new UpdateGoodsQtyRequestDTO();
        try {
            BeanUtils.populate(baseRequestDTO, request);
        } catch (Exception exception){
            return ResponseUtil.error("");
        }
        /**
         * 是否用新字段,还是沿用老逻辑
         */
        BizTypeEnum bizType = BizTypeUtil.getBizType(baseRequestDTO.getPartnerId());
        AbstractUpdateGoodsQtyService updateGoodsQtyServiceInstance = ServiceFactory.createUpdateGoodsQtyServiceInstance(bizType.getCode());
        UpdateAddGoodsBO addGoodsBOInstance = updateGoodsQtyBOAdapter.convert2UpdateAddGoodsBO(bizType.getCode(), baseRequestDTO);
        ShoppingCartGoodsBO addGoodsResponseBO = updateGoodsQtyServiceInstance.updateGoodsQty(addGoodsBOInstance);
        BaseUpdateGoodsQtyVO baseAddGoodsVO = updateGoodsQtyVOAdapter.convert2AddGoodsVO(bizType.getCode(), addGoodsResponseBO);

        return ResponseUtil.success(baseAddGoodsVO);

    }

    /**
     * 查询购物车信息
     */
    @ApiAnnotation(logMessage = "listCartGoods")
    @PostMapping(value = "/listCartGoods")
    public BaseResponse listCartGoods(@LogParams @RequestBody Map<String, Object> request) {

        ListCartGoodsRequestDTO baseRequestDTO = new ListCartGoodsRequestDTO();
        try {
            BeanUtils.populate(baseRequestDTO, request);
        } catch (Exception exception){
            return ResponseUtil.error("");
        }

        /**
         * 是否用新字段,还是沿用老逻辑
         */
        BizTypeEnum bizType = BizTypeUtil.getBizType(baseRequestDTO.getPartnerId());
        AbstractListCartGoodsService listCartGoodsServiceInstance = ServiceFactory.createListCartGoodsServiceInstance(bizType.getCode());
        ListCartGoodsBO listCartGoodsBO = listCartGoodsBOAdapter.convert2ListCartGoodsBO(bizType.getCode(), baseRequestDTO);
        ShoppingCartGoodsBO addGoodsResponseBO = listCartGoodsServiceInstance.listCartGoods(listCartGoodsBO);
        BaseListCartGoodsVO baseListCartGoodsVO = listCartGoodsVOAdapter.convert2ListCartGoodsVO(bizType.getCode(), addGoodsResponseBO);
        return ResponseUtil.success(baseListCartGoodsVO);

    }


    /**
     * 获取购物车均摊详情，点 "去支付" 时调用
     *
     * @param getShoppingCartGoodsApportionRequestVo
     * @return
     */
    @ApiAnnotation(logMessage = "getShoppingCartGoodsApportion")
    @PostMapping(value = "/getShoppingCartGoodsApportion")
    public BaseResponse getShoppingCartGoodsApportion(@Validated @LogParams @RequestBody GetShoppingCartGoodsApportionRequestVo getShoppingCartGoodsApportionRequestVo) {
        if (getShoppingCartGoodsApportionRequestVo == null || getShoppingCartGoodsApportionRequestVo.getShoppingCartInfoRequestVo() == null) {
            return ResponseUtil.error(ResponseResult.NOT_LOGIN);
        }
        ShoppingCartInfoRequestVo shoppingCartInfoRequestVo = getShoppingCartGoodsApportionRequestVo.getShoppingCartInfoRequestVo();
        return getInstanceByRequest(shoppingCartInfoRequestVo).
                getShoppingCartGoods(shoppingCartInfoRequestVo,
                        getShoppingCartGoodsApportionRequestVo.getPremiumExchangeActivity());
    }


    private ShoppingCartNewService getInstanceByRequest(BaseRequestVo requestVo) {
        if(requestVo.getChannelType() != null && OrderChannelType.SAASMALL.getCode().equals(requestVo.getChannelType())) {
            return SDKCommonBaseContextWare.getBean(ShoppingCartMallServiceImpl.class);
        } else {
            return getInstanceBySessionId(requestVo.getSessionId());
        }
    }

    private ShoppingCartNewService getInstanceBySessionId(String sessionId) {

        AssortmentCustomerInfoVo assortmentCustomerInfoVo = customerInfoManager.getCustomerInfoByObject(sessionId);
        if (assortmentCustomerInfoVo == null || StringUtils.isBlank(assortmentCustomerInfoVo.getIappId())) {
            return getInstanceByIAppId(IappIdType.IBZ_DC_XCX.getCode());
        }
        String iAppId = assortmentCustomerInfoVo.getIappId();
        return getInstanceByIAppId(iAppId);
    }

    private ShoppingCartNewService getInstanceByIAppId(String iAppId) {
        if (IappIdType.WC_XCX.getCode().equals(iAppId)) {
            //围餐
            return SDKCommonBaseContextWare.getBean(ShoppingCartMealServiceImpl.class);
        }
        return SDKCommonBaseContextWare.getBean(ShoppingCartNewServiceImpl.class);
    }

    /**
     * 清空购物车{技术支持用}
     */
    @ApiAnnotation(logMessage = "clear/goods")
    @PostMapping(value = "/clearGoods")
    public BaseResponse clearGoods(@Validated @LogParams @RequestBody ShoppingCartClearToolsRequestVo request) {
        return SDKCommonBaseContextWare.getBean(ShoppingCartToolsServiceImpl.class).clear(request);
    }


    /**
     * 线下订单查询接口
     */
    @ApiAnnotation(logMessage = "/getMemberInfo")
    @PostMapping(value = "/getMemberInfo")
    public BaseResponse getMemberInfo(@LogParams @RequestBody GetMemberInfoRequestDto request) {
        return SDKCommonBaseContextWare.getBean(ShoppingCartNewServiceImpl.class).getMemberInfo(request);
    }

}
