package com.willalp.app.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.willalp.app.domain.HsAppHomeData;
import com.willalp.app.domain.vo.AppConfigVo;
import com.willalp.app.domain.vo.HsAppHomeDataVo;
import com.willalp.app.mapper.HsAppHomeDataMapper;
import com.willalp.app.service.IHsAppHomeDataService;
import com.willalp.common.exception.base.BaseException;
import com.willalp.common.utils.DateUtils;
import com.willalp.common.utils.StringUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * app首页数据Service业务层处理
 *
 * @author willalp
 * @date 2022-01-18
 */
@Service
public class HsAppHomeDataServiceImpl extends ServiceImpl<HsAppHomeDataMapper, HsAppHomeData> implements IHsAppHomeDataService {
    @Resource
    private HsAppHomeDataMapper hsAppHomeDataMapper;

    /**
     * 查询app首页数据列表
     *
     * @param hsAppHomeData app首页数据
     * @return app首页数据
     */
    @Override
    public List<HsAppHomeData> selectHsAppHomeDataList(HsAppHomeData hsAppHomeData) {
        hsAppHomeData.setHomeParentId("0");
        List<HsAppHomeData> notInParentIds = hsAppHomeDataMapper.selectList(new QueryWrapper<HsAppHomeData>()
                .notIn("home_parent_id", 0L));
        List<HsAppHomeData> hsAppHomeData1 = hsAppHomeDataMapper.selectHsAppHomeDataList(hsAppHomeData);
        hsAppHomeData1.forEach(item ->
                notInParentIds.forEach(itemP -> {
                    if (item.getHomeContentId().equals(itemP.getHomeParentId())) {
                        item.setHsAppHomeData(itemP);
                    }
                }));
        return hsAppHomeData1;
    }

    @Override
    public Long saveHsAppHomeData(HsAppHomeData appHomeData) throws BaseException {
        String idStr;
        for (; ; ) {
            idStr = IdWorker.getIdStr();
            HsAppHomeData byId = this.getById(idStr);
            if (null == byId) {
                appHomeData.setHomeContentId(String.valueOf(idStr));
                break;
            }
        }
        appHomeData.setCreateTime(DateUtils.getNowDate());
        if (this.save(appHomeData)) {
            return Long.valueOf(idStr);
        } else {
            throw new BaseException("app.home.config.save.error", new Object[]{appHomeData.toString()});
        }
    }


    @Override
    public AppConfigVo selectAppConfigVo(Long homeId) {
        //临时固定HOMEID
        homeId = 1516289132930359298L;
        //树表中父级ID 不能为空
        if (ObjectUtils.isEmpty(homeId)) {
            throw new BaseException("app.home.config.homeId.null", new Long[]{homeId});
        }
        //查询 父级ID 对应的 所有子集
        List<HsAppHomeDataVo> hsAppHomeData = hsAppHomeDataMapper.selectAppConfigVo(homeId);
        if (hsAppHomeData.size() == 0) {
            System.out.println("size=0：" + hsAppHomeData.toString());
        }
        //获取 在第一位的父级集合
        HsAppHomeDataVo parentData = hsAppHomeData.get(0);
        AppConfigVo appConfigVo;
        //不为空则 创建 伪类对象 并 copy 然后在list中删除
        if (ObjectUtil.isNotNull(parentData)) {
            appConfigVo = new AppConfigVo();
            BeanUtil.copyProperties(parentData, appConfigVo);
            hsAppHomeData.remove(0);
        } else {
            throw new BaseException("app.home.config.null", new Long[]{homeId});
        }
        //初始化所有部分的集合
        List<HsAppHomeDataVo> copyList1 = new ArrayList<>();
        List<HsAppHomeDataVo> copyList2 = new ArrayList<>();
        List<HsAppHomeDataVo> copyList3 = new ArrayList<>();
        int listSize = hsAppHomeData.size();
       /*使用外大内小双重循环 外循环使用查询出来数据的初始长度 保证外循环会大于内循环
        内循环每add一个就remove减小内循环长度 提升运行速度*/
        for (int i = 0; i < listSize; i++) {
            for (HsAppHomeDataVo hsAppHomeDatum : hsAppHomeData) {
                if (1 == hsAppHomeDatum.getHomeGroupType()) {
                    copyList1.add(hsAppHomeDatum);
                    hsAppHomeData.remove(hsAppHomeDatum);
                    break;
                } else if (2 == hsAppHomeDatum.getHomeGroupType()) {
                    copyList2.add(hsAppHomeDatum);
                    hsAppHomeData.remove(hsAppHomeDatum);
                    break;
                } else if (3 == hsAppHomeDatum.getHomeGroupType()) {
                    copyList3.add(hsAppHomeDatum);
                    hsAppHomeData.remove(hsAppHomeDatum);
                    break;
                }
            }
        }
//        appConfigVo.setTopImg(copyList1);
//        appConfigVo.setMiddleIcon(copyList2);
//        appConfigVo.setBottomList(copyList3);
        return appConfigVo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveAppConfig(AppConfigVo appConfigVo) {
        if (ObjectUtil.isNull(appConfigVo)) {
            throw new BaseException("app.home.config.vo.null", new Object[]{appConfigVo});
        }
        List<HsAppHomeData> bottomList = appConfigVo.getBottomList();
        List<HsAppHomeData> saveList = new ArrayList<>();
        List<HsAppHomeData> updateList = new ArrayList<>();
        bottomList.forEach(item -> {
            if (StringUtils.isBlank(item.getHomeContentId())) {
                saveList.add(item);
            } else {
                updateList.add(item);
            }
        });
        try {
            if (0 != saveList.size()) {
                this.saveBatch(saveList);
            }
            if (0 != updateList.size()) {
                this.updateBatchById(updateList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("暂存失败");
        }
        //使用线程池 异步执行 修改或新增操作.
        //threadPool.submit(new AppConfigSaveThreadTools(appConfigVo, 3, this));
        return true;
    }

}
