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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.base.bo.*;
import com.zhongzheng.modules.base.domain.ProfileTp;
import com.zhongzheng.modules.base.domain.ProfileTpBusiness;
import com.zhongzheng.modules.base.mapper.ProfileTpMapper;
import com.zhongzheng.modules.base.service.IProfileTpBusinessService;
import com.zhongzheng.modules.base.service.IProfileTpService;
import com.zhongzheng.modules.base.vo.ProfileTpVo;
import com.zhongzheng.modules.course.bo.CourseChapterBusinessAddBo;
import com.zhongzheng.modules.course.domain.CourseChapter;
import com.zhongzheng.modules.course.domain.CourseChapterBusiness;
import com.zhongzheng.modules.course.domain.CourseChapterSection;
import com.zhongzheng.modules.course.service.ICourseChapterSectionService;
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 org.springframework.util.CollectionUtils;

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

/**
 * 资料模板Service业务层处理
 *
 * @author hjl
 * @date 2021-11-19
 */
@Service
public class ProfileTpServiceImpl extends ServiceImpl<ProfileTpMapper, ProfileTp> implements IProfileTpService {

    @Autowired
    private IProfileTpBusinessService iProfileTpBusinessService;

    @Autowired
    private ProfileTpMapper profileTpMapper;


    @Override
    public ProfileTpVo queryById(Long profileTpId){
        ProfileTp db = this.baseMapper.selectById(profileTpId);
        return BeanUtil.toBean(db, ProfileTpVo.class);
    }

    @Override
    public List<ProfileTpVo> queryList(ProfileTpQueryBo bo) {
        LambdaQueryWrapper<ProfileTp> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), ProfileTp::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), ProfileTp::getCode, bo.getCode());
        lqw.in(bo.getStatus() != null, ProfileTp::getStatus, bo.getStatus());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<ProfileTpVo> selectList(ProfileTpQueryBo bo) {
        return profileTpMapper.selectList(bo);
    }

    @Override
    public List<String> selectAllUseGoods(ProfileTpQueryBo bo) {
        List<ProfileTpVo> list = profileTpMapper.selectList(bo);
        List<String> strList = new ArrayList<>();
        for(int i=0;i<list.size();i++){
            if(Validator.isNotEmpty(list.get(i).getGoodsIds())){
                List<String> idList = Arrays.asList(list.get(i).getGoodsIds().split(","));
                strList.addAll(idList);
            }
        }
        LinkedHashSet<String> hashSet = new LinkedHashSet<>(strList);
        ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
        return listWithoutDuplicates;
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(ProfileTpAddBo bo) {
        ProfileTp add = BeanUtil.toBean(bo, ProfileTp.class);
        validEntityBeforeSave(add);
        add.setCode(ServletUtils.getEncoded("ZL"));
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean result = this.save(add);
        if(bo.getBusinessList()!=null){
            Collection<ProfileTpBusiness> coll = new HashSet<>();
            for(int i=0;i<bo.getBusinessList().size();i++){
                ProfileTpBusiness addItem = BeanUtil.toBean(bo.getBusinessList().get(i), ProfileTpBusiness.class);
                addItem.setProfileTpId(add.getProfileTpId());
                coll.add(addItem);
            }
            iProfileTpBusinessService.saveBatch(coll);
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(ProfileTpEditBo bo) {
        ProfileTp update = BeanUtil.toBean(bo, ProfileTp.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!= null){
            iProfileTpBusinessService.remove(new LambdaQueryWrapper<ProfileTpBusiness>().eq(ProfileTpBusiness::getProfileTpId, bo.getProfileTpId()));
            Collection<ProfileTpBusiness> coll = new HashSet<>();
            for(int i=0;i<bo.getBusinessList().size();i++){
                ProfileTpBusiness addItem = BeanUtil.toBean(bo.getBusinessList().get(i), ProfileTpBusiness.class);
                addItem.setProfileTpId(bo.getProfileTpId());
                coll.add(addItem);
            }
            iProfileTpBusinessService.saveBatch(coll);
        }
        return this.updateById(update);
    }

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

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

    @Override
    public ProfileTpVo queryByGoodsId(Long goodsId) {
        ProfileTpQueryBo profileTpQueryBo = new ProfileTpQueryBo();
        profileTpQueryBo.setGoodsId(goodsId);
        List<ProfileTpVo> profileTpVos = profileTpMapper.selectList(profileTpQueryBo);
        if (!CollectionUtils.isEmpty(profileTpVos)){
            return profileTpVos.get(0);
        }else {
            return null;
        }
    }


}
