package com.fs.app.controller;


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.app.annotation.Login;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.param.BaseQueryParam;
import com.fs.common.utils.StringUtils;
import com.fs.erp.domain.ErpGoodsStock;
import com.fs.erp.dto.ErpGoodsStockQueryRequert;
import com.fs.erp.dto.ErpGoodsStockQueryResponse;
import com.fs.erp.service.IErpGoodsService;
import com.fs.store.domain.*;
import com.fs.store.dto.StoreProductGroupDTO;
import com.fs.store.param.*;
import com.fs.store.service.*;
import com.fs.store.vo.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Api("商品中心")
@RestController
@RequestMapping(value="/app/product")
public class ProductController extends  AppBaseController {

    @Autowired
    private IFsStoreProductService productService;
    @Autowired
    private IFsStoreProductGroupService productGroupService;
    @Autowired
    private IFsStoreProductCategoryService categoryService;
    @Autowired
    private IFsStoreProductAttrService attrService;

    @Autowired
    private IFsStoreProductAttrValueService attrValueService;
    @Autowired
    private IFsStoreCartService cartService;
    @Autowired
    private IFsStoreOrderService orderService;
    @Autowired
    private IFsStoreProductRelationService productRelationService;
    @Autowired
    IErpGoodsService goodsService;
    /**
     * 获取用户信息
     * @param request
     * @return     */
    @ApiOperation("获取分类")
    @GetMapping("/getProductCate")
    public R getProductCate(HttpServletRequest request){
        try {
            FsStoreProductCategory param=new FsStoreProductCategory();
            param.setIsShow(1);
            param.setIsDel(0);
            List<FsStoreProductCategory> list=categoryService.selectFsStoreProductCategoryListQuery(param);
            return R.ok().put("data",list);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }
    @ApiOperation("获取分类")
    @GetMapping("/getProductCateByPid")
    public R getProductCateByPid(@RequestParam(value="pid") Long pid, HttpServletRequest request){
        try {
            FsStoreProductCategory param=new FsStoreProductCategory();
            param.setIsShow(1);
            param.setIsDel(0);
            param.setPid(pid);
            List<FsStoreProductCategory> list=categoryService.selectFsStoreProductCategoryListQuery(param);
            return R.ok().put("data",list);
        } catch (Exception e){
            return R.error("操作异常");
        }
    }

    @ApiOperation("获取商品列表")
    @GetMapping("/getProducts")
    public R getProducts(FsStoreProductQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        param.setIsDisplay(1);
        List<FsStoreProductListQueryVO> productList=productService.selectFsStoreProductListQuery(param);
        PageInfo<FsStoreProductListQueryVO> listPageInfo=new PageInfo<>(productList);
        return R.ok().put("data",listPageInfo);
    }
    @ApiOperation("获取商品详情")
    @GetMapping("/getProductDetails")
    public R getProductDetails(@RequestParam(value="productId") Long productId){
        FsStoreProductQueryVO product=productService.selectFsStoreProductByIdQuery(productId);
        if(product==null){
            return R.error("商品不存在或已下架");
        }
        List<FsStoreProductAttr> productAttr=attrService.selectFsStoreProductAttrByProductId(product.getProductId());
        List<FsStoreProductAttrValue> productValues=attrValueService.selectFsStoreProductAttrValueByProductId(product.getProductId());
//        for(FsStoreProductAttrValue value:productValues){
//            if(StringUtils.isEmpty(value.getGroupBarCode())){
//                //单品
//                ErpGoodsStockQueryRequert request=new ErpGoodsStockQueryRequert();
//                request.setBarcode(value.getBarCode());
//               // ErpGoodsStockQueryResponse response=goodsService.getGoodsStock(request);
////                if(response.getStocks()!=null){
////                    Integer stocks=0;
////                    for(ErpGoodsStock stock:response.getStocks()){
////                        Double goodsStock=Double.parseDouble(stock.getSalable_qty());
////                        stocks+=goodsStock.intValue();
////                    }
////                    if(stocks<=0){
////                        value.setStock(0);
////                        attrValueService.updateFsStoreProductAttrValue(value);
////                        productService.updateStock(productId);
////                    }
////                    else{
////                        //更新库存
////                        value.setStock(stocks);
////                        attrValueService.updateFsStoreProductAttrValue(value);
////                        productService.updateStock(productId);
////                    }
////
////                }
//            }
//            else{
//                //组合码
//                FsStoreProductGroup group=productGroupService.selectFsStoreProductGroupByBarCode(value.getGroupBarCode());
//                if(group!=null){
//                    Integer totalStock=0;
//                    JSONArray jsonArray= JSONUtil.parseArray(group.getProducts());
//                    List<StoreProductGroupDTO> productGroupDTOS=JSONUtil.toList(jsonArray, StoreProductGroupDTO.class);
//                    if(productGroupDTOS!=null){
//                        for(StoreProductGroupDTO dto:productGroupDTOS){
//                            FsStoreProductAttrValue attrValue=attrValueService.selectFsStoreProductAttrValueById(dto.getId());
//                            ErpGoodsStockQueryRequert request=new ErpGoodsStockQueryRequert();
//                            request.setBarcode(attrValue.getBarCode());
//                            ErpGoodsStockQueryResponse response=goodsService.getGoodsStock(request);
//                            if(response.getStocks()!=null){
//                                Integer stocks=0;
//                                for(ErpGoodsStock stock:response.getStocks()){
//                                    Double goodsStock=Double.parseDouble(stock.getSalable_qty());
//                                    stocks+=goodsStock.intValue();
//                                }
//                                if(stocks<=0){
//                                    attrValue.setStock(0);
//                                    attrValueService.updateFsStoreProductAttrValue(attrValue);
//                                }
//                                else{
//                                    //更新库存
//                                    attrValue.setStock(stocks);
//                                    attrValueService.updateFsStoreProductAttrValue(attrValue);
//                                }
//                                totalStock+=stocks;
//                            }
//                        }
//                    }
//                    value.setStock(totalStock);
//                    attrValueService.updateFsStoreProductAttrValue(value);
//                    productService.updateStock(productId);
//
//                }
//
//            }
//        }
        //获取用户的TOKEN写入足迹
        String userId=getUserId();
        if(userId!=null){
            FsStoreProductRelation productRelation=new FsStoreProductRelation();
            productRelation.setIsDel(0);
            productRelation.setUserId(Long.parseLong(userId));
            productRelation.setProductId(product.getProductId());
            productRelation.setType("foot");
            List<FsStoreProductRelation> productRelations=productRelationService.selectFsStoreProductRelationList(productRelation);
            if(productRelations!=null&&productRelations.size()>0){
                FsStoreProductRelation relation=productRelations.get(0);
                relation.setUpdateTime(new Date());
                productRelationService.updateFsStoreProductRelation(relation);
            }
            else{
                FsStoreProductRelation relation=new FsStoreProductRelation();
                relation.setUserId(Long.parseLong(userId));
                relation.setIsDel(0);
                relation.setProductId(product.getProductId());
                relation.setUpdateTime(new Date());
                relation.setType("foot");
                relation.setCreateTime(new Date());
                relation.setUpdateTime(new Date());
                productRelationService.insertFsStoreProductRelation(relation);
            }
        }
        return R.ok().put("product",product).put("productAttr",productAttr).put("productValues",productValues);
    }

    @Login
    @ApiOperation("添加购物车")
    @PostMapping("/addCart")
    public R addCart(@Validated @RequestBody FsStoreCartParam cartParam, HttpServletRequest request){
        return cartService.addCart(Long.parseLong(getUserId()),cartParam);
    }
    @Login
    @ApiOperation("获取购物车列表")
    @GetMapping("/getCarts")
    public R getCarts(HttpServletRequest request){
        List<FsStoreCartVO> carts= cartService.selectFsStoreCartListByUid(Long.parseLong(getUserId()));
        return R.ok().put("carts",carts);
    }
    @Login
    @ApiOperation("改变购物车数量")
    @PostMapping("/cartNum")
    public R cartNum(@Validated @RequestBody FsStoreCartNumParam cartParam, HttpServletRequest request){
        return cartService.changeNum(Long.parseLong(getUserId()),cartParam);
    }
    @Login
    @ApiOperation("删除购物车")
    @PostMapping("/delCart")
    public R delCart(@Validated @RequestBody FsStoreCartDelParam cartParam, HttpServletRequest request){
        return cartService.delCart(Long.parseLong(getUserId()),cartParam);
    }


    @Login
    @ApiOperation("获取商品购物车数量")
    @GetMapping("/getCartCount")
    public R getCartCount(FsStoreCartCountParam param){
        param.setUserId(Long.parseLong(getUserId()));
        Integer count=cartService.selectFsStoreCartCount(param);
        return R.ok().put("data", count);
    }

    @ApiOperation("获取推荐商品列表")
    @GetMapping("/getTuiProduct")
    public R getTuiProduct(HttpServletRequest request){
        List<FsStoreProductListQueryVO> productList=productService.selectFsStoreProductTuiQuery(10);
        return R.ok().put("data", productList);
    }
    @ApiOperation("获取喜欢商品列表")
    @GetMapping("/getGoodsProduct")
    public R getGoodsProduct(BaseQueryParam param,HttpServletRequest request){
        List<FsStoreProductListQueryVO> productList=productService.selectFsStoreProductGoodQuery(10);
        return R.ok().put("data", productList);
    }
    @ApiOperation("获取推荐商品数据")
    @GetMapping("/getTuiProducts")
    public R getTuiProducts(BaseQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsStoreProductListQueryVO> list=productService.selectFsStoreProductTuiListQuery();
        PageInfo<FsStoreProductListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);
    }
    @ApiOperation("获取喜欢商品数据")
    @GetMapping("/getGoodsProducts")
    public R getGoodsProducts(BaseQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsStoreProductListQueryVO> list=productService.selectFsStoreProductGoodListQuery();
        PageInfo<FsStoreProductListQueryVO> listPageInfo=new PageInfo<>(list);
        return R.ok().put("data",listPageInfo);

    }

    @ApiOperation("获取推广商品列表")
    @GetMapping("/getStoreProductAttrValueList")
    public R getStoreProductAttrValueList(FsStoreProductAttrValueQueryParam param, HttpServletRequest request){
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<FsStoreProductAttrValueQueryVO> productList=attrValueService.selectStoreProductAttrValueListQuery(param);
        PageInfo<FsStoreProductAttrValueQueryVO> listPageInfo=new PageInfo<>(productList);
        return R.ok().put("data",listPageInfo);
    }



}
