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 com.zhongzheng.common.core.page.TableDataInfo;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.activity.bo.*;
import com.zhongzheng.modules.activity.domain.ActivityConfiguration;
import com.zhongzheng.modules.activity.domain.ActivityGrade;
import com.zhongzheng.modules.activity.domain.ActivityGradePrivilege;
import com.zhongzheng.modules.activity.domain.ActivityGradePrivilegeCoures;
import com.zhongzheng.modules.activity.mapper.ActivityGradeMapper;
import com.zhongzheng.modules.activity.mapper.ActivityGradePrivilegeCouresMapper;
import com.zhongzheng.modules.activity.mapper.ActivityGradePrivilegeMapper;
import com.zhongzheng.modules.activity.service.IActivityGradePrivilegeCouresService;
import com.zhongzheng.modules.activity.service.IActivityGradePrivilegeService;
import com.zhongzheng.modules.activity.service.IActivityGradeService;
import com.zhongzheng.modules.activity.vo.ActivityGradeVo;
import com.zhongzheng.modules.user.service.IUserService;
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 change
 * @date 2021-05-19
 */
@Service
public class ActivityGradeServiceImpl extends ServiceImpl<ActivityGradeMapper, ActivityGrade> implements IActivityGradeService {

    @Autowired
    private ActivityGradePrivilegeCouresMapper activityGradePrivilegeCouresMapper;

    @Autowired
    private IActivityGradePrivilegeService activityGradePrivilegeService;

    @Autowired
    private IActivityGradePrivilegeCouresService activityGradePrivilegeCouresService;

    @Autowired
    private ActivityGradePrivilegeMapper activityGradePrivilegeMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private  IActivityGradeService iActivityGradeService;

    @Override
    public ActivityGradeVo queryById(Long id){
        ActivityGrade db = this.baseMapper.selectById(id);
        ActivityGradeVo activityGradeVo = BeanUtil.toBean(db, ActivityGradeVo.class);
        activityGradeVo.setActivityGradePrivilegesVo(activityGradePrivilegeMapper.selectGradePriList(activityGradeVo.getId()));
        return activityGradeVo;
    }

    @Override
    public TableDataInfo<ActivityGradeVo> queryList(ActivityGradeQueryBo bo) {
        LambdaQueryWrapper<ActivityGrade> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGrade() != null, ActivityGrade::getGrade, bo.getGrade());
        lqw.like(StrUtil.isNotBlank(bo.getGradeName()), ActivityGrade::getGradeName, bo.getGradeName());
        lqw.eq(bo.getNeedIntegralStart() != null, ActivityGrade::getNeedIntegralStart, bo.getNeedIntegralStart());
        lqw.eq(bo.getNeedIntegralEnd() != null, ActivityGrade::getNeedIntegralEnd, bo.getNeedIntegralEnd());
        lqw.eq(StrUtil.isNotBlank(bo.getRemarks()), ActivityGrade::getRemarks, bo.getRemarks());
        lqw.orderByDesc(ActivityGrade::getUpdateTime);
        List<ActivityGrade> list = this.list(lqw);
        List<ActivityGradeVo> activityGradeVos = selectGradeCourse(list);
        List<ActivityGradeVo> activityGradeVos1 = entity2Vo(activityGradeVos);
        TableDataInfo<ActivityGradeVo> listData = new TableDataInfo<>();
        listData.setCode(200);
        listData.setMsg("查询成功");
        listData.setRows(activityGradeVos1);
        listData.setTotal(baseMapper.selectCount(lqw));
        return listData;
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<ActivityGradeVo> entity2GradeVo(Collection<ActivityGrade> collection) {
        List<ActivityGradeVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, ActivityGradeVo.class))
                .collect(Collectors.toList());
        return voList;
    }

    private List<ActivityGradeVo> selectGradeCourse(List<ActivityGrade> list) {
        List<ActivityGradeVo> activityGradeVos = entity2GradeVo(list);
        for (ActivityGradeVo activityGradeVo : activityGradeVos) {
            Integer num = userService.selectUserNum(activityGradeVo.getGrade());
            activityGradeVo.setUserNum(num);
        }
        activityGradeVos.stream().forEach(a -> {
            a.setActivityGradePrivilegesVo(activityGradePrivilegeMapper.selectGradePriList(a.getId()));

        });

        return activityGradeVos;
    }

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

    public static void main(String[] args) {
        String str = "[1,2]";
        String substring = str.substring(1, 2);
        String substring1 = str.substring(3, 4);
        System.out.println("截取最后一个字符串生成的新字符串为: " + substring);//abcdef
        System.out.println("截取最后一个字符串生成的新字符串为: " + substring1);//abcdef
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(ActivityGradeAddBo bo) {
        ActivityGrade add = BeanUtil.toBean(bo, ActivityGrade.class);
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean save = iActivityGradeService.save(add);
        //添加特权类型
        if (!CollectionUtils.isEmpty(bo.getActivityGradePrivilegeAddBos())) {
            bo.getActivityGradePrivilegeAddBos().stream().forEach(p ->{
                ActivityGradePrivilege activityGradePrivilege = BeanUtil.toBean(p, ActivityGradePrivilege.class);
                activityGradePrivilege.setGradeId(add.getId());
                activityGradePrivilegeService.save(activityGradePrivilege);
                Arrays.stream(p.getCourseIds()).forEach(c -> {
                    ActivityGradePrivilegeCoures activityGradePrivilegeCoures = new ActivityGradePrivilegeCoures();
                    activityGradePrivilegeCoures.setPrivilegeId(activityGradePrivilege.getId());
                    if ("2".equals(p.getPriType())){
                        activityGradePrivilegeCoures.setStatus(2);
                    }else {
                        activityGradePrivilegeCoures.setStatus(1);
                    }
                    activityGradePrivilegeCoures.setCourseId(Convert.toLong(c));
                    activityGradePrivilegeCouresMapper.insertCouse(activityGradePrivilegeCoures);

                });
            });
        }
        //添加特权绑定的
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(ActivityGradeEditBo bo) {
        ActivityGrade update = BeanUtil.toBean(bo, ActivityGrade.class);
        update.setUpdateTime(DateUtils.getNowTime());
        validEntityBeforeSave(update);
        //修改特权类型
        activityGradePrivilegeService.removeByGrade(bo.getId());
        if (!CollectionUtils.isEmpty(bo.getActivityGradePrivilegeEditBos())) {
            updateGradePrivilege(bo);
        }
        return iActivityGradeService.updateById(update);
    }

    private void updateGradePrivilege(ActivityGradeEditBo bo) {

        bo.getActivityGradePrivilegeEditBos().stream().forEach(p ->{
                //修改
                    ActivityGradePrivilege activityGradePrivilege = BeanUtil.toBean(p, ActivityGradePrivilege.class);
                    activityGradePrivilege.setGradeId(bo.getId());
                    activityGradePrivilege.setStatus(1);
                    activityGradePrivilegeService.save(activityGradePrivilege);
                    if (p.getCourseIds() != null ) {
                        Arrays.stream(p.getCourseIds()).forEach(c -> activityGradePrivilegeCouresMapper
                                .insertCouse(new ActivityGradePrivilegeCoures().setPrivilegeId(activityGradePrivilege.getId())
                                        .setCourseId(Convert.toLong(c))));
                    }
            });
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        ArrayList<ActivityGrade> activityGradeArrayList = new ArrayList<>();
        ids.stream().forEach(id -> activityGradeArrayList.add(new ActivityGrade().setId(id)));
        return iActivityGradeService.updateBatchById(activityGradeArrayList);
    }

    @Override
    public ActivityGradeVo queryByInteger(Long bo) {

        return baseMapper.queryByInteger(bo);
    }
}
