package com.org.hktshop.controller.order;

import com.org.hktshop.base.BaseException;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.constant.CommonConstant;
import com.org.hktshop.controller.BaseController;
import com.org.hktshop.dto.HktCartBatchInfoDto;
import com.org.hktshop.entity.order.HktCart;
import com.org.hktshop.entity.user.HktUser;
import com.org.hktshop.service.order.HktCartService;
import com.org.hktshop.utils.HttpCode;
import com.org.hktshop.utils.Ret;
import com.org.hktshop.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("/cart")
@Api(tags = "购物车接口")
public class HktCartController extends BaseController {

    @Autowired
    private HktCartService hktCartService;

    /**
     * 购物车新增
     *
     * @param hktCart
     * @return
     */
    @PostMapping("/saveCart")
    @ApiOperation(value = "添加商品到购物车", notes = "添加商品到购物车")
    @ApiImplicitParam(name = CommonConstant.HKT_CART, value = "购物车header标识", dataType = "String", paramType = "header")
    public BaseResult saveCartInfo(@RequestBody HktCart hktCart, HttpServletRequest request) {
        try {
            String cartKey = request.getHeader(CommonConstant.HKT_CART);
            HktUser user = null;
            try {
                user = (HktUser) getSessionUserId(request);

            } catch (Exception ex) {
            }
            /*List<HktCart> hktCartList = hktCartService.getHktCartList(user, cartKey);
            for(HktCart hktCart1 : hktCartList){
                if(hktCart1.getGoodsId().equals(hktCart.getGoodsId()) && "1".equals(hktCart1.getIsSample()) && "1".equals(hktCart.getIsSample())){
                    return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"相同的样品不同重复添加");
                }
            }*/
            Ret ret = hktCartService.saveOrMergeHktCart(hktCart, user, cartKey);
            if (ret.isFail()) return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(), ret.getStr("msg"));
            return BaseResult.success();
        } catch (BaseException ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            return BaseResult.fail(10001, ex.getMessage());
        } catch (Exception ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /**
     * 通过goodId删除购物车商品
     *
     * @param goodId
     * @return
     */
    @GetMapping("/deleteCartByGoodId")
    @ApiOperation(value = "通过goodId删除购物车商品", notes = "通过goodId删除购物车商品")
    public BaseResult deleteCartByGoodId(@RequestParam("goodId") String goodId, HttpServletRequest request) {
        try {
            HktUser user = null;
            try {
                user = (HktUser) getSessionUserId(request);
            } catch (Exception ex) {
            }
            String cartKey = request.getHeader(CommonConstant.HKT_CART);

            hktCartService.deleteHktCartByGoodsId(goodId, user, cartKey);
            return BaseResult.success();
        } catch (Exception ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /**
     * 更新单个购物车单个商品信息
     *
     * @param hktCart
     * @return
     */
    @PostMapping("/updateCart")
    @ApiOperation(value = "更新单个购物车单个商品信息", notes = "更新单个购物车单个商品信息")
    public BaseResult updateCart(@RequestBody HktCart hktCart, HttpServletRequest request) {
        try {
            HktUser user = null;
            try {
                user = (HktUser) getSessionUserId(request);
                hktCart.setUserId(user.getId());

                String cartKey = request.getHeader(CommonConstant.HKT_CART);
                List<HktCart> hktCartList = hktCartService.getHktCartList(user, cartKey);

                for(HktCart hc : hktCartList){
                    if(hc.getSelected() == 1){
                        if("1".equals(hktCart.getIsSample()) && "0".equals(hc.getIsSample())){
                            return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"不能同时选中样品和费样品项");
                        }
                    }
                }
            } catch (Exception ex) {
            }
//            if (user == null) return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            hktCartService.updateHktCart(hktCart);
            return BaseResult.success();
        } catch (Exception ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /**
     * 购物车商品查询
     *
     * @return
     */
    @GetMapping("/getCartList")
    @ApiOperation(value = "购物车商品查询", notes = "购物车商品查询")
    @ApiImplicitParam(name = CommonConstant.HKT_CART, value = "购物车header标识", required = false, dataType = "String", paramType = "header")
    public BaseResult getCartList(HttpServletRequest request) {
        try {
            String cartKey = request.getHeader(CommonConstant.HKT_CART);
            HktUser user = null;
            try {
                user = (HktUser) getSessionUserId(request);
                if(StringUtils.isNull(user.getId())){
                    return BaseResult.fail("您不是内部账户无法查看");
                }
            } catch (Exception ex) {
            }
            if (user == null && StringUtils.isNull(cartKey))
                return BaseResult.successWithData(new ArrayList<>());

            List<HktCart> hktCartList = hktCartService.getHktCartList(user, cartKey);
            return BaseResult.successWithData(hktCartList);
        } catch (Exception ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    /**
     * 购物车本地缓存查询标识
     *
     * @return
     */
    @GetMapping("/getCartHeader")
    @ApiOperation(value = "购物车本地缓存查询标识", notes = "购物车本地缓存查询标识")
    public BaseResult getCartHeader() {
        try {
            String headerHktCart = StringUtils.getUUID();
            return BaseResult.successWithData(headerHktCart);
        } catch (Exception ex) {
            logger.error("添加商品到购物车 ex={}", ex.getMessage());
            ex.printStackTrace();
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

    @PostMapping("/batchCart")
    @ApiOperation(value = "商品批量加入购物车", notes = "商品批量加入购物车")
    public BaseResult batchCart(@RequestBody HktCartBatchInfoDto hktCartBatchInfoDto, HttpServletRequest request) {
        try {
            String cartKey = request.getHeader(CommonConstant.HKT_CART);
            HktUser user=null;
            try {
                user = (HktUser) getSessionUserId(request);
            } catch (Exception ex) {
            }
            hktCartService.batchInsert(hktCartBatchInfoDto.getGoodsInfo(), hktCartBatchInfoDto.getLanguage(), user, cartKey);
            return BaseResult.success();
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }


    /**
     * 查看购物车是否选中同一类商品
     *
     * @param hktCart
     * @return
     */
    @PostMapping("/checkCart")
    @ApiOperation(value = "查看购物车是否选中同一类商品", notes = "查看购物车是否选中同一类商品")
    public BaseResult checkCart(@RequestBody HktCart hktCart, HttpServletRequest request) {
            HktUser user = null;
            try {
                user = (HktUser) getSessionUserId(request);
                hktCart.setUserId(user.getId());

                String cartKey = request.getHeader(CommonConstant.HKT_CART);
                List<HktCart> hktCartList = hktCartService.getHktCartList(user, cartKey);
                Set<String> set = new HashSet<>();
                for(HktCart hc : hktCartList){
                    if(hc.getSelected() ==1){
                        if(set.size() == 0){
                            set.add(hc.getIsSample());
                        }else {
                            if(!set.contains(hc.getIsSample())){
                                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"不能同时选中样品与非样品!");
                            }
                        }
                    }
                }
            return BaseResult.success();
        } catch (Exception ex) {
            logger.error("查看购物车是否选中同一类商品 ex={}", ex.getMessage());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(), HttpCode.INTERNAL_SERVER_ERROR.getMsg());
        }
    }

}
