package com.org.hktshop.controller.portal.product;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.org.hktshop.Dao.Intface.IGoodsItemDao;
import com.org.hktshop.Interface.portal.product.IPortalProductService;
import com.org.hktshop.Interface.portal.product.PortalSearchService;
import com.org.hktshop.Interface.product.IHktGoodsCategoryService;
import com.org.hktshop.base.BaseResult;
import com.org.hktshop.controller.BaseController;
import com.org.hktshop.entity.Page;
import com.org.hktshop.entity.product.HktGoodItem;
import com.org.hktshop.entity.product.HktGoodsCategory;
import com.org.hktshop.entity.product.HktGoodsSeoDesc;
import com.org.hktshop.entity.product.HktSearchRemind;
import com.org.hktshop.entity.vo.HktGoodsCategoryVo;
import com.org.hktshop.utils.HttpCode;
import com.org.hktshop.utils.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author owen
 */
@RequestMapping("/product")
@RestController
public class PortalProductController extends BaseController {

    @Autowired
    private IPortalProductService portalProductService;

    @Autowired
    IHktGoodsCategoryService categoryService;

    @Autowired
    PortalSearchService portalSearchService;

    @Autowired
    private IGoodsItemDao goodsItemDao;
    @PostMapping("/appProductMenu")
    @ApiOperation(value = "小程序APP菜单")
    public Object appProductMenu() {
        return BaseResult.successWithData(categoryService.appProductMenu());
    }

    /**
     * 商品目录
     *
     * @return
     */
    @PostMapping("/selectProductMenu")
    @ApiOperation(value = "查询商品分类列表")
    public Object queryList(@RequestBody HktGoodsCategory category) {
        try {
            List<HktGoodsCategoryVo> voList = categoryService.queryCategoryVo(new HktGoodsCategory());

            if (category != null && category.getSort() != null && category.getSort() == 1) {
                List<HktGoodsCategoryVo> nList = new ArrayList<>();
                for (HktGoodsCategoryVo vo : voList) {

                    boolean isFind = false;
                    for (HktGoodsCategoryVo no : nList ) {
                        if (no.getSort().equals(vo.getSort()) && vo.getGoodsNum() > 0) {
                            no.setNameCh(no.getNameCh() + "/" + vo.getNameCh());
                            no.setNameEn(no.getNameEn() + "/" + vo.getNameEn());
                            no.getSortObj().add(vo);
                            isFind = true;
                            break;
                        }
                    }
                    if (!isFind && vo.getGoodsNum() > 0) {
                        HktGoodsCategoryVo categoryVo = new HktGoodsCategoryVo();
                        categoryVo.setNameCh(vo.getNameCh());
                        categoryVo.setNameEn(vo.getNameEn());
                        categoryVo.setSortObj(new ArrayList<>());
                        categoryVo.getSortObj().add(vo);
                        categoryVo.setSort(vo.getSort());
                        nList.add(categoryVo);
                    }
                }
                voList = nList;
            }

            List<Map<String, Object>> retValue = new ArrayList<>();
            for (HktGoodsCategoryVo vo : voList) {

                Map<String, Object> objectMap = new HashMap<>();
                if ("1".equals(category.getLanguage()))
                    objectMap.put("nameCh", vo.getNameCh());
                else
                    objectMap.put("nameCh", vo.getNameEn());
                objectMap.put("id", vo.getId());
//                objectMap.put("onSaleNum", vo.getOnSaleNum());
                objectMap.put("onSaleNum", vo.getGoodsNum());
                objectMap.put("image", vo.getImage());

                if (vo.getSortObj()!= null) {
                    List<Map<String, Object>> sortObj = new ArrayList<>();
                    for (HktGoodsCategoryVo obj : vo.getSortObj()) {
                        Map<String, Object> tempMap = new HashMap<>();
                        tempMap.put("image", obj.getImage());
                        if ("1".equals(category.getLanguage()))
                            tempMap.put("nameCh", obj.getNameCh());
                        else
                            tempMap.put("nameCh", obj.getNameEn());
                        tempMap.put("id", obj.getId());
                        tempMap.put("onSaleNum", obj.getGoodsNum());

                        List<Map<String, Object>> subCategory = new ArrayList<>();
                        for (HktGoodsCategory sub : obj.getSubCategory()) {
                            Map<String, Object> subTempMap = new HashMap<>();

                            if ("1".equals(category.getLanguage()))
                                subTempMap.put("nameCh", sub.getNameCh());
                            else
                                subTempMap.put("nameCh", sub.getNameEn());
                            subTempMap.put("id", sub.getId());
                            subTempMap.put("onSaleNum", sub.getGoodsNum());
                            subTempMap.put("goodsImage",sub.getImage());
                            subCategory.add(subTempMap);
                        }
                        tempMap.put("subCategory", subCategory);
                        sortObj.add(tempMap);
                    }
                    objectMap.put("sortObj", sortObj);
                }

                List<Map<String, Object>> subCategoryOne = new ArrayList<>();
                for (HktGoodsCategory sub : vo.getSubCategory()) {
                    Map<String, Object> subTempMap = new HashMap<>();

                    if(sub.getGoodsNum() > 0){
                        if ("1".equals(category.getLanguage()))
                            subTempMap.put("nameCh", sub.getNameCh());
                        else
                            subTempMap.put("nameCh", sub.getNameEn());
                        subTempMap.put("id", sub.getId());
                        subTempMap.put("onSaleNum", sub.getGoodsNum());
                        subTempMap.put("hot",sub.getIsHot());
                        subCategoryOne.add(subTempMap);
                    }
                }
                objectMap.put("subCategory", subCategoryOne);
                retValue.add(objectMap);
            }
            List<Map<String, Object>> categoryList = new ArrayList<>();
            if(category != null && category.getSort() == null){
                for(Map<String, Object> map : retValue){
                    String subCategory = JSON.toJSONString(map.get("subCategory"));
                    List<Object> list = JSON.parseArray(subCategory, Object.class);
                    if(list.size() > 0){
                        categoryList.add(map);
                    }
                }
                return BaseResult.successWithData(categoryList);
            }
            return BaseResult.successWithData(retValue);
        } catch (Exception ex) {
            logger.error("selectProductMenu 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 商品详情
     *
     * @return
     */
    @PostMapping("/findProduct")
    @ApiOperation(value = "查询商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品主键", required = true),
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object findProduct(@RequestBody HktGoodItem hktGoods) {
        try {
            if (StringUtils.isNull(hktGoods.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            HktGoodItem hktGoodItem = portalProductService.findProduct(hktGoods);
            /*HktGoodItem h = new HktGoodItem();
            h.setId(hktGoods.getId());
            h.setScore(1);
            goodsItemDao.updateGoodsScore(h);*/
            return BaseResult.successWithData(hktGoodItem);
        } catch (Exception ex) {
            logger.error("findProduct 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 分页查询商品
     *
     * @return
     */
    @PostMapping("/selectProductLike")
    @ApiOperation(value = "查询商品分类列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
            @ApiImplicitParam(name = "queryValue", value = "模糊查询条件", required = true),
            @ApiImplicitParam(name = "categoryId", value = "分类id"),
            @ApiImplicitParam(name = "sort", value = "排序字段"),
            @ApiImplicitParam(name = "goodsType", value = "商品类型"),
    })
    public Object selectProductLike(@RequestBody HktGoodItem hktGoods) {
        try{
            if(!StringUtils.isNull(hktGoods.getQueryValue())){
                HktSearchRemind hktSearchRemind = new HktSearchRemind();
                hktSearchRemind.setName(hktGoods.getQueryValue());
                hktSearchRemind.setLanguageId(hktGoods.getLanguage());
                if(hktGoods.getQueryValue().matches("[\u4E00-\u9FA5]+") && hktGoods.getQueryValue().length() >= 2){
                    portalSearchService.addSearchByProductLike(hktSearchRemind);
                }else if(!hktGoods.getQueryValue().matches("[\u4E00-\u9FA5]+") && hktGoods.getQueryValue().length() > 2){
                    portalSearchService.addSearchByProductLike(hktSearchRemind);
                }
            }
        }catch (Exception e){
            logger.error("商品检索調用接口错误(不影响流程): error = {}", e.toString());
        }
        try {
            Page<HktGoodItem> hktGoodsPageItemPage = portalProductService.selectProductLike(hktGoods);
            return BaseResult.successWithData(hktGoodsPageItemPage);
        } catch (Exception ex) {
            logger.error("商品检索错误: error = {}", ex.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 商品搜索标题
     *
     * @return
     */
    @PostMapping("/selectTitle")
    @ApiOperation(value = "查询商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object selectTitle(@RequestBody HktGoodsSeoDesc hktGoodsSeoDesc) {
        try {
            if (StringUtils.isNull(hktGoodsSeoDesc.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            Page<HktGoodsSeoDesc> page = portalProductService.selectTitle(hktGoodsSeoDesc);
            return BaseResult.successWithData(page);
        } catch (Exception ex) {
            logger.error("selectTitle 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 特价商品首页展示
     *
     * @return
     */
    @PostMapping("/selectSpecialProduct")
    @ApiOperation(value = "特价商品首页展示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object selectIndexSpecialProduct(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            //0 普通 1 特价(special) 2 热销(hot) 3 采购专区(purchase)
            hktGoodItem.setGoodsType(1);
            Page<HktGoodItem> page = portalProductService.selectProductLike(hktGoodItem);
            removeAttr(page);
            return BaseResult.successWithData(page);
        } catch (Exception ex) {
            logger.error("selectSpecialProduct 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 热门商品首页展示
     *
     * @return
     */
    @PostMapping("/selectHotProduct")
    @ApiOperation(value = "热门商品首页展示列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object selectIndexHotProduct(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            //0 普通 1 特价 2 热销 3 采购专区
            hktGoodItem.setGoodsType(2);
            Page<HktGoodItem> page = portalProductService.selectProductLike(hktGoodItem);
            removeAttr(page);
            return BaseResult.successWithData(page);
        } catch (Exception ex) {
            logger.error("selectHotProduct 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 采购专区商品首页展示
     *
     * @return
     */
    @PostMapping("/selectPurchaseProduct")
    @ApiOperation(value = "采购专区商品首页展示")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object selectIndexPurchaseProduct(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            //0 普通 1 特价 2 热销 3 采购专区
            hktGoodItem.setGoodsType(3);
            Page<HktGoodItem> page = portalProductService.selectProductLike(hktGoodItem);
            removeAttr(page);
            return BaseResult.successWithData(page);
        } catch (Exception ex) {
            logger.error("selectPurchaseProduct 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 统计商品数量
     *
     * @return
     */
    @PostMapping("/statistics")
    @ApiOperation(value = "商品數量")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true)
    })
    public Object statisticsCountProduct(@RequestBody Map map) {
        try {
            if (StringUtils.isNull(map.get("language"))) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            Map<String, Object> objectMap = portalProductService.statisticsCountProduct(map);
            return BaseResult.successWithData(objectMap);
        } catch (Exception ex) {
            logger.error("statistics 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 相似商品
     *
     * @return
     */
    @PostMapping("/resemble")
    @ApiOperation(value = "相似商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
            @ApiImplicitParam(name = "categoryId", value = "分类id", required = true),
            @ApiImplicitParam(name = "specParam", value = "参数规格", required = true),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "条数", required = true),
            @ApiImplicitParam(name = "id", value = "当前商品id", required = true),
            @ApiImplicitParam(name = "price", value = "当前商品价格", required = true),
    })
    public Object resembleProduct(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
           /* if (StringUtils.isNull(hktGoodItem.getSpecParam())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode(),"参数规格不能为空！");
            }*/
            Page<Map<String, Object>> mapPage = portalProductService.resembleProduct(hktGoodItem);
            return BaseResult.successWithData(mapPage);
        } catch (Exception ex) {
            logger.error("resemble 异常: ex={}",ex.getMessage() );
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 买它的客户还买了
     *
     * @return
     */
    @PostMapping("/other")
    @ApiOperation(value = "买它的客户还买了")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
            @ApiImplicitParam(name = "categoryId", value = "分类id", required = true)
    })
    public Object otherProduct(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            Page<Map<String, Object>> mapPage = portalProductService.otherProduct(hktGoodItem);
            return BaseResult.successWithData(mapPage);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }

    /**
     * 查出分类为一级得菜单
     *
     * @return
     */
    @PostMapping("/category")
    @ApiOperation(value = "一级分类商品名称")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
    })
    public Object prodectCategory(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            List<Map<String, Object>> list = portalProductService.prodectCategory(hktGoodItem);
            return BaseResult.successWithData(list);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 查出分类为一级得菜单
     *
     * @return
     */
    @PostMapping("/guesgs")
    @ApiOperation(value = "猜你喜欢(购物车)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
            @ApiImplicitParam(name = "categoryId", value = "分类id集合", required = true),
            @ApiImplicitParam(name = "id", value = "商品id集合", required = true),
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "显示数量", required = true)
    })
    public Object prodectGuesgsYouLike(@RequestBody HktGoodItem hktGoodItem) {
        try {
            if (StringUtils.isNull(hktGoodItem.getLanguage())) {
                return BaseResult.fail(HttpCode.BAD_REQUEST.getCode());
            }
            Page<HktGoodItem> page = portalProductService.prodectGuesgsYouLike(hktGoodItem);
            return BaseResult.successWithData(page);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 筛选器
     * @return
     */
    @PostMapping("/filterList")
    @ApiOperation(value = "筛选器")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类id集合", required = true),
    })
    public Object filterList(@RequestBody HktGoodItem hktGoodItem) {
        try {
            Object list = portalProductService.filterList(hktGoodItem);
            return BaseResult.successWithData(list);
        } catch (Exception ex) {
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    /**
     * 小程序筛选
     *
     * @return
     */
    @PostMapping("/screen")
    @ApiOperation(value = "小程序筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "language", value = "语言类型", required = true),
            @ApiImplicitParam(name = "queryValue", value = "模糊查询条件", required = true),
            @ApiImplicitParam(name = "categoryId", value = "分类id"),
            @ApiImplicitParam(name = "sort", value = "排序字段"),
            @ApiImplicitParam(name = "goodsType", value = "商品类型"),
    })
    public Object screen(@RequestBody HktGoodItem hktGoods) {
        try {
            return BaseResult.successWithData(portalProductService.screen(hktGoods));
        } catch (Exception ex) {
            logger.error("商品检索错误: error = {}", ex.toString());
            return BaseResult.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode());
        }
    }


    private void removeAttr(Page<HktGoodItem> page) {
        List<HktGoodItem> records = page.getRecords();
        page.setObject(null);
        if (records.size() > 0) {
            for (HktGoodItem hktGoodItem : records) {
//                hktGoodItem.setPriceTemplate("");
                hktGoodItem.setQueryValue("");
            }
        }
    }
}
