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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.zhongzheng.common.core.page.TableDataInfo;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationAddBo;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationEditBo;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationQueryBo;
import com.zhongzheng.modules.activity.domain.ActivityConfiguration;
import com.zhongzheng.modules.activity.domain.ActivityConfigurationCourse;
import com.zhongzheng.modules.activity.mapper.ActivityConfigurationCourseMapper;
import com.zhongzheng.modules.activity.mapper.ActivityConfigurationMapper;
import com.zhongzheng.modules.activity.service.IActivityConfigurationCourseService;
import com.zhongzheng.modules.activity.service.IActivityConfigurationService;
import com.zhongzheng.modules.activity.service.IActivityConfigurationUseService;
import com.zhongzheng.modules.activity.vo.ActivityConfigurationVo;
import com.zhongzheng.modules.course.bo.CourseQueryBo;
import com.zhongzheng.modules.course.vo.CourseConfigurationVo;
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 change
 * @date 2021-05-17
 */
@Service
public class ActivityConfigurationServiceImpl extends ServiceImpl<ActivityConfigurationMapper, ActivityConfiguration> implements IActivityConfigurationService {

    @Autowired
    private ActivityConfigurationCourseMapper activityConfigurationCourseMapper;

    @Autowired
    private IActivityConfigurationUseService activityConfigurationUseService;

    @Autowired
    private IActivityConfigurationCourseService activityConfigurationCourseService;

    @Autowired
    private  IActivityConfigurationService iActivityConfigurationService;

    @Override
    public ActivityConfigurationVo queryById(Long id){
        ActivityConfigurationVo activityConfigurationVo = baseMapper.selectConfigures(id);
        Integer num  = activityConfigurationUseService.countConfig(activityConfigurationVo.getId());
        activityConfigurationVo.setUserNumber(num);
        List<Long> course = activityConfigurationCourseService.selectConfiguraList(activityConfigurationVo.getId());
        activityConfigurationVo.setCourses(course);
        return activityConfigurationVo;

    }

    @Override
    public TableDataInfo<ActivityConfigurationVo> queryList(ActivityConfigurationQueryBo bo) {
        Collection<ActivityConfigurationVo> activityConfigurationVos = baseMapper.selectConfiguraList(bo);
        for (ActivityConfigurationVo activityConfigurationVo : activityConfigurationVos) {
            Integer num  = activityConfigurationUseService.countConfig(activityConfigurationVo.getId());
            activityConfigurationVo.setUserNumber(num);
            List<Long> course = activityConfigurationCourseService.selectConfiguraList(activityConfigurationVo.getId());
            activityConfigurationVo.setCourses(course);
        }

        TableDataInfo<ActivityConfigurationVo> list = new TableDataInfo<>();
        list.setRows(entity2Vo(activityConfigurationVos));
        list.setCode(HttpStatus.HTTP_OK);
        list.setMsg("查询成功");
        list.setTotal(baseMapper.selectConfiguraCount(bo));
        return list;
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(ActivityConfigurationAddBo bo) {
        //新增活动
        ActivityConfiguration activityConfiguration = BeanUtil.toBean(bo, ActivityConfiguration.class);
        activityConfiguration.setCreateTime(DateUtils.getNowTime());
        activityConfiguration.setUpdateTime(DateUtils.getNowTime());
        activityConfiguration.setStatus(4);
        int insert = baseMapper.insert(activityConfiguration);
        if (bo.getCoursesId() != null) {
            //绑定课程
            insertConfigCourse(activityConfiguration.getId(), bo.getCoursesId());
        }
        return true;
    }

    private void insertConfigCourse(Long id, String[] coursesId) {
        Arrays.stream(coursesId).forEach(e -> {
            ActivityConfigurationCourse activityConfigurationCourse = new ActivityConfigurationCourse()
                    .setConfigurationId(id).setCourseId(Convert.toLong(e));
            activityConfigurationCourseMapper.insertCourse(activityConfigurationCourse);
        });
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(ActivityConfigurationEditBo bo) {
        ActivityConfiguration update = BeanUtil.toBean(bo, ActivityConfiguration.class);
        update.setUpdateTime(DateUtils.getNowTime());
        //修改绑定课程
        if (bo.getCoursesId() != null){
            updateConfigCourse(bo);
        }
        return iActivityConfigurationService.updateById(update);
    }

    private void updateConfigCourse(ActivityConfigurationEditBo bo) {
        activityConfigurationCourseMapper.deleteById(bo.getId());
        Arrays.stream(bo.getCoursesId()).forEach(e ->{
            ActivityConfigurationCourse activityConfigurationCourse = new ActivityConfigurationCourse()
                    .setConfigurationId(bo.getId()).setCourseId(Convert.toLong(e));
            activityConfigurationCourseMapper.insertCourse(activityConfigurationCourse);
        });
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        ArrayList<ActivityConfiguration> activityConfigurations = new ArrayList<>();
        ids.stream().forEach(id -> activityConfigurations.add(new ActivityConfiguration().setId(id).setStatus(0).setUpdateTime(DateUtils.getNowTime())));
        return iActivityConfigurationService.updateBatchById(activityConfigurations);
    }

    @Override
    public List<ActivityConfigurationVo> queryIssueList(ActivityConfigurationQueryBo bo) {
        bo.setStartTime(DateUtils.getNowTime());
        List<ActivityConfigurationVo> courseConfigurationVos = entityCourseVo(baseMapper.selectConfiguraIssueList(bo));
        return courseConfigurationVos;
    }

    @Override
    public List<ActivityConfigurationVo> listConfiguration(CourseQueryBo bo) {
        bo.setStartTime(DateUtils.getNowTime());
        List<ActivityConfigurationVo> activityConfigurations =baseMapper.selectlistConfiguration(bo) ;
        return activityConfigurations;
    }

    @Override
    public int selectCount(Long goodsId, Long activity) {
        return baseMapper.selectCountActivity(goodsId,activity);
    }

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