package com.kmall.api.service;

import com.google.common.collect.Maps;
import com.kmall.api.dao.ApiGoodsMapper;
import com.kmall.api.dto.GoodsDetailDto;
import com.kmall.api.entity.*;
import com.kmall.api.entity.mk.MkStorePromStatVo;
import com.kmall.api.entity.mk.MkStorePromVisitorsVo;
import com.kmall.api.entity.mk.MkStorePromVo;
import com.kmall.api.service.mk.ApiMkStorePromService;
import com.kmall.api.service.mk.ApiMkStorePromStatService;
import com.kmall.api.service.mk.ApiMkStorePromVisitorsService;
import com.kmall.api.util.StockUtil;
import com.kmall.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;


@Service
public class ApiGoodsService {
    @Autowired
    private ApiGoodsMapper goodsDao;
    @Autowired
    private ApiGoodsIssueService goodsIssueService;
    @Autowired
    private ApiAttributeService attributeService;
    @Autowired
    private ApiCommentService commentService;
    @Autowired
    private ApiUserService userService;
    @Autowired
    private ApiCommentPictureService commentPictureService;
    @Autowired
    private ApiCollectService collectService;
    @Autowired
    private ApiFootprintService footprintService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private ApiFreightService apiFreightService;
    @Autowired
    private ApiMkStorePromVisitorsService apiMkStorePromVisitorsService;
    @Autowired
    private ApiBrandService apiBrandService;
    @Autowired
    private ApiGoodsSpecificationService goodsSpecificationService;
    @Autowired
    private ApiProductService productService;
    @Autowired
    private ApiGoodsGalleryService goodsGalleryService;
    @Autowired
    private ApiCartService cartService;
    @Autowired
    private ApiMkStorePromStatService apiMkStorePromStatService;
    @Autowired
    private ApiMkStorePromService apiMkStorePromService;


    public GoodsVo queryObject(Long id) {
        return goodsDao.queryObject(id);
    }
    public GoodsVo queryObjectByStoreId(Long id,Long storeId) {
        return goodsDao.queryObjectByStoreId(id,storeId);
    }


    public List<GoodsVo> queryList(Map<String, Object> map) {
        return goodsDao.queryList(map);
    }


    public int queryTotal(Map<String, Object> map) {
        return goodsDao.queryTotal(map);
    }


    public void save(GoodsVo goods) {
        goodsDao.save(goods);
    }


    public void update(GoodsVo goods) {
        goodsDao.update(goods);
    }


    public void delete(Integer id) {
        goodsDao.delete(id);
    }


    public void deleteBatch(Integer[] ids) {
        goodsDao.deleteBatch(ids);
    }

    public List<GoodsVo> queryHotGoodsList(Map<String, Object> map) {
        return goodsDao.queryHotGoodsList(map);
    }

    public List<GoodsVo> queryCatalogProductList(Map<String, Object> map) {
        return goodsDao.queryCatalogProductList(map);
    }

    public Integer selectCountByCatalogProductList(Map<String, Object> map){
        return goodsDao.selectCountByCatalogProductList(map);
    }

    public Map detail(GoodsVo info, GoodsDetailDto detailDto){
        Long userId = detailDto.getUserId();
        Long referrer = detailDto.getReferrer();
        String merchSn = detailDto.getMerchSn();
        Long storeId = detailDto.getStoreId();
        Integer promId = detailDto.getPromId();
        Long id = detailDto.getId();

        Map<String, Object> resultObj = Maps.newHashMap();
        BrandVo brand = apiBrandService.queryObject(info.getBrand_id());
        resultObj.put("brand", brand);

        List<Map> specificationList = goodsSpecificationService.queryByGoodsIdGroupByNames(id);

        //查询产品信息
        Map param = Maps.newHashMap();
        param.put("goods_id", id);
        param.put("store_id", storeId);
        List<ProductVo> productEntityList = productService.queryList(param);
        //团购
        List<GoodsGalleryVo> gallery = goodsGalleryService.queryList(param);
        resultObj.put("gallery", gallery);

        Map ngaParam = Maps.newHashMap();
        ngaParam.put("fields", "nga.value, na.name");
        ngaParam.put("sidx", "nga.id");
        ngaParam.put("order", "asc");
        ngaParam.put("goods_id", id);
        List<AttributeVo> attribute = attributeService.queryList(ngaParam);
        //商品问答
        Map issueParam = Maps.newHashMap();
        issueParam.put("merch_sn", merchSn);
        issueParam.put("store_id", storeId);
        List<GoodsIssueVo> issue = goodsIssueService.queryList(issueParam);
        //商品评论
        param.put("value_id", id);
        param.put("type_id", 0);
        Integer commentCount = commentService.queryTotal(param);
        List<CommentVo> hotComment = commentService.queryList(param);
        Map commentInfo = Maps.newHashMap();
        if (null != hotComment && hotComment.size() > 0) {
            UserVo commentUser = userService.queryObject(hotComment.get(0).getUserId());
            commentInfo.put("content", hotComment.get(0).getContent());
            commentInfo.put("add_time", DateUtils.timeToStr(hotComment.get(0).getAddTime(), DateUtils.PATTERN_YYYY_MM_DD_HH_MM));
            commentInfo.put("nickname", commentUser.getNickname());
            commentInfo.put("avatar", commentUser.getAvatar());
            Map paramPicture = Maps.newHashMap();
            paramPicture.put("comment_id", hotComment.get(0).getId());
            List<CommentPictureVo> commentPictureEntities = commentPictureService.queryList(paramPicture);
            commentInfo.put("pic_list", commentPictureEntities);
        }
        Map comment = Maps.newHashMap();
        comment.put("count", commentCount);
        comment.put("data", commentInfo);
        //当前用户是否收藏
        Map collectParam = Maps.newHashMap();
        collectParam.put("user_id", userId);
        collectParam.put("value_id", id);
        collectParam.put("type_id", 0);
        Integer userHasCollect = collectService.queryTotal(collectParam);
        if (userHasCollect > 0) {
            userHasCollect = 1;
        }
        if(userId!=null) {
            //记录用户的足迹
            FootprintVo footprintEntity = new FootprintVo();
            footprintEntity.setAdd_time(System.currentTimeMillis() / 1000);
            footprintEntity.setGoods_brief(info.getGoods_brief());
            footprintEntity.setList_pic_url(info.getList_pic_url());
            footprintEntity.setGoods_id(id);
            footprintEntity.setName(info.getName());
            footprintEntity.setRetail_price(info.getRetail_price());
            footprintEntity.setUser_id(userId);
            if (null != referrer) {
                footprintEntity.setReferrer(referrer);
            } else {
                footprintEntity.setReferrer(0L);
            }
            footprintService.save(footprintEntity);

            String isStockShare = StockUtil.getIsStockShareByGoodsVo(info);
            Map cartMap = Maps.newHashMap();
            cartMap.put("user_id", userId);
            cartMap.put("goods_id", id);
            cartMap.put("store_id", storeId);
            cartMap.put("isStockShare", isStockShare);
            cartMap.put("goodsBizType", info.getGoodsBizType());
            List<CartVo> cartVoList = cartService.queryList(cartMap);
            resultObj.put("cartNumber", cartVoList.size() != 0 ? cartVoList.get(0).getNumber():0);
        }

        FreightEntity freightEntity = apiFreightService.queryObjectByGoodsId(id, storeId);

        Integer stockNum = StockUtil.setStockNumByGoodsVo(info);

        if(com.kmall.common.utils.StringUtils.isNotEmpty(String.valueOf(promId))){
            MkStorePromVo mkStorePromVo = apiMkStorePromService.queryObject(promId);
            MkStorePromStatVo mkStorePromStatVo = new MkStorePromStatVo();
            if(mkStorePromVo != null) {
                //记录渠道推广浏览量
                MkStorePromStatVo statVo = apiMkStorePromStatService.queryObjectByPromId(mkStorePromVo.getPromId());
                //记录推广访客数据
                MkStorePromVisitorsVo visitorsVo = apiMkStorePromVisitorsService.queryObjectByPromIdAndUserId(promId ,
                        Integer.parseInt(String.valueOf(userId)));
                if(visitorsVo == null){
                    MkStorePromVisitorsVo promVisitorsVo = new MkStorePromVisitorsVo();
                    promVisitorsVo.setPromId(promId);
                    promVisitorsVo.setUserId(Integer.parseInt(String.valueOf(userId)));
                    promVisitorsVo.setIsValid("0");
                    promVisitorsVo.setCreateTime(new Date());
                    promVisitorsVo.setModTime(new Date());
                    apiMkStorePromVisitorsService.save(promVisitorsVo);
                }
                Integer visitNum = apiMkStorePromVisitorsService.queryCountByPromId(mkStorePromVo.getPromId());
                mkStorePromStatVo.setReferrer(Integer.parseInt(String.valueOf(referrer)));
                mkStorePromStatVo.setVisitPageDeep(1);
                if(statVo != null){
                    mkStorePromStatVo.setBrowseNum(statVo.getBrowseNum()+1);
                    mkStorePromStatVo.setVisitNum(visitNum);
                    mkStorePromStatVo.setRelaBrowseNum(statVo.getRelaBrowseNum()+1);//连带浏览量
                    mkStorePromStatVo.setRelaVisitorNum(visitNum);//连带访客量
                    mkStorePromStatVo.setTransVisitorNum(visitNum);//转发访客量:用户转发了带有推广id的商品，其他的用户点击的访客量
                    mkStorePromStatVo.setPromStatId(statVo.getPromStatId());
                    apiMkStorePromStatService.update(mkStorePromStatVo);
                }else {
                    mkStorePromStatVo.setStoreId(Integer.parseInt(String.valueOf(storeId)));
                    mkStorePromStatVo.setPromId(mkStorePromVo.getPromId());
                    mkStorePromStatVo.setBrowseNum(1);
                    mkStorePromStatVo.setVisitNum(visitNum);
                    mkStorePromStatVo.setRelaBrowseNum(1);//连带浏览量
                    mkStorePromStatVo.setRelaVisitorNum(visitNum);//连带访客量
                    mkStorePromStatVo.setTransVisitorNum(visitNum);//转发访客量:用户转发了带有推广id的商品，其他的用户点击的访客量
                    mkStorePromStatVo.setIsValid("0");
                    apiMkStorePromStatService.save(mkStorePromStatVo);
                }
            }
        }
        info.setStock_num(stockNum);
        resultObj.put("info", info);

        resultObj.put("attribute", attribute);
        resultObj.put("userHasCollect", userHasCollect);
        resultObj.put("issue", issue);
        resultObj.put("comment", comment);
        resultObj.put("specificationList", specificationList);
        resultObj.put("productList", productEntityList);
        resultObj.put("stockNum", stockNum);
        resultObj.put("defaultFreight", freightEntity != null? freightEntity.getDefaultFreight() :0);
        return resultObj;
    }
}
