package cn.com.ty.lift.system.framework.runner;

import cn.com.ty.lift.common.constants.ApiConstants;
import cn.com.ty.lift.common.constants.RedisConstants;
import cn.com.ty.lift.common.model.AreaCode;
import cn.com.ty.lift.system.settings.dao.entity.GlobalSet;
import cn.com.ty.lift.system.settings.dao.mapper.GlobalSetMapper;
import cn.com.ty.lift.system.settings.service.GlobalSetService;
import cn.com.ty.lift.system.user.service.IAreaCodeService;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangyuan
 * @date 2019-12-03
 * @description
 */
@Component
@Slf4j
public class SystemServiceRunner implements ApplicationRunner {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private IAreaCodeService iAreaCodeService;

    @Resource
    private GlobalSetService globalSetService;

    @Resource
    private GlobalSetMapper globalSetMapper;

    @Override
    public void run(ApplicationArguments args) {
        //初始化省、市、区信息列表
        //initAreaList();
        //初始化全局设置到redis
        initGlobalSet();
    }

    /**
     * @description 初始化省、市、区信息列表
     * @date 2019/12/3 6:31 PM
     */
    public void initAreaList() {
        //组装省、市、区树形结构列表
        List<AreaCode> areaCodeList = iAreaCodeService.areaTree();
        redisTemplate.opsForValue().set(RedisConstants.RK_AREA_LIST, areaCodeList);
        log.info("初始化区域信息列表{}", JSONUtil.parse(areaCodeList));
    }

    /**
     * 初始化全局设置数据到redis
     */
    public void initGlobalSet() {
        //获取已通过申请通过的公司列表
        List<Long> companyIds = globalSetMapper.companyIds();
        //获取全部全局设置列表
        List<GlobalSet> globalSetList = globalSetService.list();
        //将已通过公司的全局设置筛选出来
        List<GlobalSet> globalSets = globalSetList.stream()
                .filter(globalSet -> companyIds.contains(globalSet.getCompanyId()))
                .collect(Collectors.toList());
        //向redis批量set数据
        redisTemplate.executePipelined((RedisCallback<String>) connection -> {
            for (GlobalSet globalSet : globalSets) {
                String companyId = globalSet.getCompanyId().toString();
                String code = globalSet.getCode();
                connection.hSet((companyId + "_globalSet").getBytes(), code.getBytes(), globalSet.getValue().toString().getBytes());
            }
            return null;
        });
    }
}
