package com.zhongzheng.modules.goods.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.course.bo.CourseChapterSectionListAddBo;
import com.zhongzheng.modules.course.domain.CourseChapterSection;
import com.zhongzheng.modules.course.mapper.CourseChapterMapper;
import com.zhongzheng.modules.goods.bo.*;
import com.zhongzheng.modules.goods.domain.Goods;
import com.zhongzheng.modules.goods.domain.GoodsAttached;
import com.zhongzheng.modules.goods.domain.GoodsAuditionConfig;
import com.zhongzheng.modules.goods.domain.GoodsCourse;
import com.zhongzheng.modules.goods.mapper.GoodsMapper;
import com.zhongzheng.modules.goods.service.IGoodsAttachedService;
import com.zhongzheng.modules.goods.service.IGoodsAuditionConfigService;
import com.zhongzheng.modules.goods.service.IGoodsCourseService;
import com.zhongzheng.modules.goods.service.IGoodsService;
import com.zhongzheng.modules.goods.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 商品Service业务层处理
 *
 * @author hjl
 * @date 2021-10-12
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private IGoodsCourseService iGoodsCourseService;

    @Autowired
    private IGoodsAttachedService iGoodsAttachedService;

    @Autowired
    private IGoodsAuditionConfigService iGoodsAuditionConfigService;

    @Override
    public GoodsVo queryById(Long goodsId){
        Goods db = this.baseMapper.selectById(goodsId);
        GoodsVo goodsVo = BeanUtil.toBean(db, GoodsVo.class);
        //试听配置
        if(db.getGoodsAuditionConfig()!=null){
            goodsVo.setAuditionList(JSON.parseArray(db.getGoodsAuditionConfig(), GoodsAuditionConfigVo.class));
        }
        //播放设置
        if(db.getGoodsPlayConfig()!=null){
            goodsVo.setGoodsPlayConfigVo(JSON.parseObject(db.getGoodsPlayConfig(), GoodsPlayConfigVo.class));
        }
        //拍照设置
        if(db.getGoodsPhotographConfig()!=null){
            goodsVo.setGoodsPhotographConfigVo(JSON.parseObject(db.getGoodsPhotographConfig(), GoodsPhotographConfigVo.class));
        }
        //试卷试做配置
        if(db.getGoodsExamConfig()!=null){
            goodsVo.setExamConfigList(JSON.parseArray(db.getGoodsExamConfig(), GoodsExamConfigVo.class));
        }
        return goodsVo;
    }

    @Override
    public List<GoodsVo> selectList(GoodsQueryBo bo) {
        return goodsMapper.selectList(bo);
    }

    @Override
    public GoodsVo selectDetail(Long goodsId) {
        return goodsMapper.selectDetail(goodsId);
    }

    @Override
    public List<GoodsVo> queryList(GoodsQueryBo bo) {
        LambdaQueryWrapper<Goods> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getYear() != null, Goods::getYear, bo.getYear());
        lqw.eq(bo.getSupplyId() != null, Goods::getSupplyId, bo.getSupplyId());
        lqw.eq(bo.getGoodsType() != null, Goods::getGoodsType, bo.getGoodsType());
        lqw.eq(bo.getEducationTypeId() != null, Goods::getEducationTypeId, bo.getEducationTypeId());
        lqw.eq(bo.getBusinessId() != null, Goods::getBusinessId, bo.getBusinessId());
        lqw.eq(bo.getSchoolId() != null, Goods::getSchoolId, bo.getSchoolId());
        lqw.eq(bo.getMajorId() != null, Goods::getMajorId, bo.getMajorId());
        lqw.like(StrUtil.isNotBlank(bo.getGoodsName()), Goods::getGoodsName, bo.getGoodsName());
        lqw.eq(bo.getStandPrice() != null, Goods::getStandPrice, bo.getStandPrice());
        lqw.eq(bo.getLowestPrice() != null, Goods::getLowestPrice, bo.getLowestPrice());
        lqw.eq(bo.getStatus() != null, Goods::getStatus, bo.getStatus());
        lqw.eq(bo.getValidityStartTime() != null, Goods::getValidityStartTime, bo.getValidityStartTime());
        lqw.eq(bo.getValidityEndTime() != null, Goods::getValidityEndTime, bo.getValidityEndTime());
        lqw.eq(bo.getStudyStartTime() != null, Goods::getStudyStartTime, bo.getStudyStartTime());
        lqw.eq(bo.getStudyEndTime() != null, Goods::getStudyEndTime, bo.getStudyEndTime());
        lqw.eq(StrUtil.isNotBlank(bo.getCertificateIds()), Goods::getCertificateIds, bo.getCertificateIds());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduce()), Goods::getIntroduce, bo.getIntroduce());
        lqw.eq(StrUtil.isNotBlank(bo.getSuitableObject()), Goods::getSuitableObject, bo.getSuitableObject());
        lqw.eq(StrUtil.isNotBlank(bo.getBuyNote()), Goods::getBuyNote, bo.getBuyNote());
        lqw.eq(StrUtil.isNotBlank(bo.getPcDetailHtml()), Goods::getPcDetailHtml, bo.getPcDetailHtml());
        lqw.eq(StrUtil.isNotBlank(bo.getMobileDetailHtml()), Goods::getMobileDetailHtml, bo.getMobileDetailHtml());
        lqw.eq(bo.getGoodsStatus() != null, Goods::getGoodsStatus, bo.getGoodsStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getCoverUrl()), Goods::getCoverUrl, bo.getCoverUrl());
        lqw.eq(bo.getClassHours() != null, Goods::getClassHours, bo.getClassHours());
        lqw.eq(StrUtil.isNotBlank(bo.getStandPriceJson()), Goods::getStandPriceJson, bo.getStandPriceJson());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<GoodsVo> entity2Vo(Collection<Goods> collection) {
        List<GoodsVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, GoodsVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Goods> page = (Page<Goods>)collection;
            Page<GoodsVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(GoodsAddBo bo) {
        Goods add = BeanUtil.toBean(bo, Goods.class);
        add.setCode(ServletUtils.getEncoded("SP"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        //试听设置列表
        if(bo.getAuditionList()!=null){
            add.setGoodsAuditionConfig(JSON.toJSONString(bo.getAuditionList()));
        }
        //播放设置
        if(bo.getPlayConfig()!=null){
            add.setGoodsPlayConfig(JSON.toJSONString(bo.getPlayConfig()));
        }
        //拍照设置
        if(bo.getPhotographConfig()!=null){
            add.setGoodsPhotographConfig(JSON.toJSONString(bo.getPhotographConfig()));
        }
        boolean result = this.save(add);
        //课程列表
        if(bo.getCourseList()!=null){
            Collection<GoodsCourse> coll = new HashSet<>();
            for(int i=0;i<bo.getCourseList().size();i++){
                GoodsCourseAddBo item = bo.getCourseList().get(i);
                GoodsCourse addItem = new GoodsCourse();
                addItem.setGoodsId(add.getGoodsId());
                addItem.setCourseId(item.getCourseId());
                addItem.setSort(item.getSort());
                coll.add(addItem);
            }
            iGoodsCourseService.saveBatch(coll);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertBankByAddBo(GoodsBankAddBo bo) {
        Goods add = BeanUtil.toBean(bo, Goods.class);
        add.setCode(ServletUtils.getEncoded("SP"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        //试卷试做设置列表
        if(bo.getExamConfigList()!=null){
            add.setGoodsExamConfig(JSON.toJSONString(bo.getExamConfigList()));
        }
        boolean result = this.save(add);
        if(bo.getBankList()!=null){
            Collection<GoodsAttached> coll = new HashSet<>();
            for(int i=0;i<bo.getBankList().size();i++){
                GoodsAttachedAddBo item = bo.getBankList().get(i);
                GoodsAttached addItem = BeanUtil.toBean(item, GoodsAttached.class);
                addItem.setGoodsId(add.getGoodsId());
                addItem.setCreateTime(DateUtils.getNowTime());
                addItem.setUpdateTime(DateUtils.getNowTime());
                coll.add(addItem);
            }
            iGoodsAttachedService.saveBatch(coll);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(GoodsEditBo bo) {
        Goods update = BeanUtil.toBean(bo, Goods.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        //课程列表
        if(bo.getCourseList()!=null){
            iGoodsCourseService.remove(new LambdaQueryWrapper<GoodsCourse>().eq(GoodsCourse::getGoodsId, bo.getGoodsId()));
            Collection<GoodsCourse> coll = new HashSet<>();
            for(int i=0;i<bo.getCourseList().size();i++){
                GoodsCourseAddBo item = bo.getCourseList().get(i);
                GoodsCourse addItem = new GoodsCourse();
                addItem.setGoodsId(update.getGoodsId());
                addItem.setCourseId(item.getCourseId());
                addItem.setSort(item.getSort());
                coll.add(addItem);
            }
            iGoodsCourseService.saveBatch(coll);
        }
        //试听列表
        if(bo.getAuditionList()!=null&&bo.getAuditionList().size()>0){
            update.setGoodsAuditionConfig(JSON.toJSONString(bo.getAuditionList()));
        }
        //播放设置
        if(bo.getPlayConfig()!=null){
            update.setGoodsPlayConfig(JSON.toJSONString(bo.getPlayConfig()));
        }
        //拍照设置
        if(bo.getPhotographConfig()!=null){
            update.setGoodsPhotographConfig(JSON.toJSONString(bo.getPhotographConfig()));
        }
        return this.updateById(update);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateBankByEditBo(GoodsBankEditBo bo) {
        Goods update = BeanUtil.toBean(bo, Goods.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBankList()!=null){
            iGoodsAttachedService.remove(new LambdaQueryWrapper<GoodsAttached>().eq(GoodsAttached::getGoodsId, bo.getGoodsId()));
            Collection<GoodsAttached> coll = new HashSet<>();
            for(int i=0;i<bo.getBankList().size();i++){
                GoodsAttachedEditBo item = bo.getBankList().get(i);
                GoodsAttached addItem = BeanUtil.toBean(item, GoodsAttached.class);
                addItem.setGoodsId(update.getGoodsId());
                addItem.setCreateTime(DateUtils.getNowTime());
                addItem.setUpdateTime(DateUtils.getNowTime());
                coll.add(addItem);
            }
            iGoodsAttachedService.saveBatch(coll);
        }
        //试卷试做设置列表
        if(bo.getExamConfigList()!=null&&bo.getExamConfigList().size()>0){
            update.setGoodsExamConfig(JSON.toJSONString(bo.getExamConfigList()));
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Goods entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
