package com.ruoyi.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonParser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiniu.util.Json;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.GoodsProductVO;
import com.ruoyi.mall.domain.vo.IndexGoodsVO;
import com.ruoyi.mall.domain.vo.MemberCollectVO;
import com.ruoyi.mall.mapper.MallGoodsGoodsMapper;
import com.ruoyi.mall.mapper.MallGoodsProductMapper;
import com.ruoyi.mall.mapper.MallMemberSearchHistoryMapper;
import com.ruoyi.mall.mapper.MallMemberUserMapper;
import com.ruoyi.mall.service.*;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 商品Service业务层处理
 *
 * @author chang
 * @date 2021-11-25
 */
@Service
public class MallGoodsGoodsServiceImpl implements IMallGoodsGoodsService
{
    @Autowired
    private MallGoodsGoodsMapper mallGoodsGoodsMapper;
    @Autowired
    private MallGoodsProductMapper mallGoodsProductMapper;

    @Autowired
    private IMallMemberSearchHistoryService searchHistoryService;

    @Autowired
    IMallImgService imgService;

    @Autowired
    IMallOrderCommentService orderCommentService;

    @Autowired
    IMallMemberUserService userService;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public MallGoodsGoods selectMallGoodsGoodsById(Long id)
    {
        MallGoodsGoods goods = mallGoodsGoodsMapper.selectMallGoodsGoodsById(id);
        List<MallGoodsProduct> list = mallGoodsProductMapper.selectMallGoodsProductByGoodsId(id);
        goods.setProList(list);
        return goods;
    }

    /**
     * 查询商品列表
     *
     * @param mallGoodsGoods 商品
     * @return 商品
     */
    @Override
    public List<MallGoodsGoods> selectMallGoodsGoodsList(MallGoodsGoods mallGoodsGoods)
    {
        List<MallGoodsGoods> list = mallGoodsGoodsMapper.selectMallGoodsGoodsList(mallGoodsGoods);
        for (MallGoodsGoods goodsVO: list) {
            MallImg img = new MallImg();
            img.setResId(goodsVO.getId());
            img.setType("0");
            List<String> imgList = imgService.selectMallImgUrlVoList(img);
            goodsVO.setGoodsBanner(JSON.toJSONString(imgList));

            MallImg img1 = new MallImg();
            img1.setResId(goodsVO.getId());
            img1.setType("1");
            List<String> imgList1 = imgService.selectMallImgUrlVoList(img1);
            goodsVO.setGoodsDetail(JSON.toJSONString(imgList1));
        }
        return list;
    }

    /**
     * 查询商品列表
     *
     * @param mallGoodsGoods 商品
     * @return 商品
     */
    @Transactional
    @Override
    public PageInfo<IndexGoodsVO> selectMallGoodsGoodsListByPage(Integer pageNum,Integer pageSize, MallGoodsGoods mallGoodsGoods, String userId)
    {
        if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsName()) && org.apache.commons.lang3.StringUtils.isNotBlank(userId)){
            MallMemberSearchHistory search = new MallMemberSearchHistory();
            search.setGoodName(mallGoodsGoods.getGoodsName());
            search.setUserId(Long.parseLong(userId));
            List<MallMemberSearchHistory> list = searchHistoryService.selectMallMemberSearchHistoryList(search);
            if (list.size() > 0){
                MallMemberSearchHistory result = list.get(0);
                result.setCreateAt(DateUtils.getTime());
                searchHistoryService.updateMallMemberSearchHistory(result);
            }else {
                MallMemberSearchHistory searchHistory = new MallMemberSearchHistory();
                searchHistory.setCreateAt(DateUtils.getTime());
                searchHistory.setGoodName(mallGoodsGoods.getGoodsName());
                searchHistory.setUserId(Long.parseLong(userId));
                searchHistoryService.insertMallMemberSearchHistory(searchHistory);
            }
        }
        PageHelper.startPage(pageNum,pageSize);
        List<IndexGoodsVO> list = mallGoodsGoodsMapper.selectMallGoodsGoodsListVO(mallGoodsGoods);
        PageInfo<IndexGoodsVO> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    /**
     * 新增商品
     *
     * @param mallGoodsGoods 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertMallGoodsGoods(MallGoodsGoods mallGoodsGoods)
    {
        mallGoodsGoods.setCreateAt(DateUtils.getTime());
        int count = mallGoodsGoodsMapper.insertMallGoodsGoods(mallGoodsGoods);
        if (count>0){
            for (MallGoodsProduct goodsProduct: mallGoodsGoods.getProList()){
                goodsProduct.setGoodsId(mallGoodsGoods.getId());
                goodsProduct.setCreateAt(DateUtils.getTime());
                mallGoodsProductMapper.insertMallGoodsProduct(goodsProduct);
            }



            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsBanner())){
                String goodsBanner = mallGoodsGoods.getGoodsBanner();
                goodsBanner = goodsBanner.replace("[","");
                goodsBanner = goodsBanner.replace("]","");
                goodsBanner = goodsBanner.replace("\"","");
                String[] urlList = goodsBanner.split(",");
                for (String urlStr: urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("0");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsDetail())){
                String goodsDetail = mallGoodsGoods.getGoodsDetail();
                goodsDetail = goodsDetail.replace("[","");
                goodsDetail = goodsDetail.replace("]","");
                goodsDetail = goodsDetail.replace("\"","");
                String[] urlList = goodsDetail.split(",");
                for (String urlStr: urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("1");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }
        }
        return count;
    }

    /**
     * 修改商品
     *
     * @param mallGoodsGoods 商品
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMallGoodsGoods(MallGoodsGoods mallGoodsGoods)
    {
        mallGoodsGoods.setUpdateAt(DateUtils.getTime());
        int count = mallGoodsGoodsMapper.updateMallGoodsGoods(mallGoodsGoods);
        if (count>0){
            mallGoodsProductMapper.removeByGoodsId(mallGoodsGoods.getId());
            for (MallGoodsProduct product: mallGoodsGoods.getProList()){
                product.setDelFlag("0");
                mallGoodsProductMapper.updateMallGoodsProduct(product);
            }

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsBanner())){
                //删除来的图片重新添加
                MallImg deleteImgVO = new MallImg();
                deleteImgVO.setType("0");
                deleteImgVO.setResId(mallGoodsGoods.getId());
                imgService.deleteMallImgByImgVO(deleteImgVO);

                String goodsBanner = mallGoodsGoods.getGoodsBanner();
                goodsBanner = goodsBanner.replace("[","");
                goodsBanner = goodsBanner.replace("]","");
                goodsBanner = goodsBanner.replace("\"","");
                String[] urlList = goodsBanner.split(",");
                for (String urlStr: urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("0");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }

            if (!StringUtils.isEmpty(mallGoodsGoods.getGoodsDetail())){
                //删除来的图片重新添加
                MallImg deleteImgVO1 = new MallImg();
                deleteImgVO1.setType("1");
                deleteImgVO1.setResId(mallGoodsGoods.getId());
                imgService.deleteMallImgByImgVO(deleteImgVO1);

                String goodsDetail = mallGoodsGoods.getGoodsDetail();
                goodsDetail = goodsDetail.replace("[","");
                goodsDetail = goodsDetail.replace("]","");
                goodsDetail = goodsDetail.replace("\"","");
                String[] urlList = goodsDetail.split(",");
                for (String urlStr: urlList) {
                    MallImg img = new MallImg();
                    img.setImg(urlStr);
                    img.setType("1");
                    img.setResId(mallGoodsGoods.getId());
                    img.setCreateAt(DateUtils.getTime());
                    imgService.insertMallImg(img);
                }
            }
        }
        return count;
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteMallGoodsGoodsByIds(Long[] ids)
    {
        return mallGoodsGoodsMapper.deleteMallGoodsGoodsByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteMallGoodsGoodsById(Long id)
    {
        return mallGoodsGoodsMapper.deleteMallGoodsGoodsById(id);
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsBySales() {
        return mallGoodsGoodsMapper.selectMallGoodsBySales();
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsByCreatTime() {
        return mallGoodsGoodsMapper.selectMallGoodsByCreatTime();
    }

    @Override
    public List<IndexGoodsVO> selectMallGoodsByhot() {
        return mallGoodsGoodsMapper.selectMallGoodsByhot();
    }

    @Override
    public IndexGoodsVO selectMallGoodsGoodsByIdVO(Map<String, Object> params) {
        IndexGoodsVO goods = mallGoodsGoodsMapper.selectMallGoodsGoodsByIdVO(Long.parseLong(params.get("goodsId").toString()));
        if (goods != null){
            List<GoodsProductVO> list = mallGoodsProductMapper.selectMallGoodsProductByGoodsIdVO(Long.parseLong(params.get("goodsId").toString()));
            goods.setProList(list);

            MallImg mallImg = new MallImg();
            mallImg.setResId(goods.getId());
            mallImg.setType("0");
            List<String> bannerlist = imgService.selectMallImgUrlVoList(mallImg);
            goods.setBanners(bannerlist);

            mallImg.setType("1");
            List<String> detailList = imgService.selectMallImgUrlVoList(mallImg);
            goods.setDetailUrl(detailList);
        }

        int commentTotle = orderCommentService.selectCountByGoodsId(Long.parseLong(params.get("goodsId").toString()));
        goods.setCommentTotle(commentTotle);

        //评论图片
        List<Map <String, Object>> commtentList = orderCommentService.selectTwoRecordByGoodsId(Long.parseLong(params.get("goodsId").toString()));
        for (Map <String, Object> map: commtentList) {
            String classId = map.get("id").toString();
            MallImg mallImg = new MallImg();
            mallImg.setResId(Long.parseLong(classId));
            mallImg.setType("2");
//            List<String> bannerlist = imgService.selectMallImgUrlVoList(mallImg);
            List <String> imgList = imgService.selectMallImgUrlVoList(mallImg);
            map.put("imgList",imgList);
        }
        goods.setCommentList(commtentList);

        //收藏状态
        goods.setIsCollect("0");
        if (StringUtils.isNotBlank(MapUtils.getString(params, "userId"))){
            String userId = params.get("userId").toString();
            if (StringUtils.isEmpty(userId)){
                goods.setIsCollect("0");
            }else {
                MemberCollectVO collectVO = new MemberCollectVO();
                collectVO.setGoodsId(Long.parseLong(params.get("goodsId").toString()));
                collectVO.setMemberId(Long.parseLong(userId));
                MemberCollectVO resultCollect = userService.selectIsCollectBy(collectVO);
                if (ObjectUtils.isNotEmpty(resultCollect)){
                    goods.setIsCollect("1");
                }
            }
        }
        return goods;
    }
}
