package com.boman.gen.controller;

import com.boman.common.core.web.controller.BaseController;
import com.boman.common.core.web.domain.AjaxResult;
import com.boman.common.redis.RedisKey;
import com.boman.common.redis.service.RedisService;
import com.boman.gen.domain.GenTable;
import com.boman.gen.domain.GenTableColumn;
import com.boman.gen.domain.GenTableRelation;
import com.boman.gen.service.IGenTableColumnService;
import com.boman.gen.service.IGenTableRelationService;
import com.boman.gen.service.IGenTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.boman.common.core.utils.obj.ObjectUtils.requireNonNull;

/**
 * @author shiqian
 * @description 获取gen_table
 * @date 2021年03月17日 16:44
 **/
@RestController
@RequestMapping("/init")
public class MyController extends BaseController {

    @Autowired
    private IGenTableService genTableService;
    @Autowired
    private IGenTableColumnService genTableColumnService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IGenTableRelationService genTableRelationService;

    /**
     * 功能描述: 查询代码生成列表，table中封装columnList
     *
     * @param genTable 查询条件
     * @return AjaxResult
     */
    @GetMapping("/loadTable")
    public AjaxResult loadTable(GenTable genTable) {
        List<GenTable> tableList = genTableService.selectGenTableList(genTable);
        requireNonNull(tableList);

        // load table and tableColumn
        List<Long> tableIdList = tableList.stream().map(GenTable::getTableId).collect(Collectors.toList());
        List<GenTableColumn> genTableColumns = genTableColumnService.listByTableIdList(tableIdList);
        requireNonNull(genTableColumns);
        packTableAndInsertToRedis(tableList, genTableColumns);

        List<GenTableRelation> relationList = genTableRelationService.selectGenTableRelationList(new GenTableRelation());
        requireNonNull(relationList);
        // load gen_table_relation表数据到redis
        redisService.setCacheObject(RedisKey.RELATION_INFO, relationList, 12L, TimeUnit.DAYS);

        // load tableRelation
        packRelationAndInsertToRedis(tableList, relationList, genTableColumns);
        return AjaxResult.success(tableList);
    }

    /**
     * 功能描述: 把主表关联的附表的信息和附表的字段信息存进redis
     *
     * @param tableList    tableList 所有表对象信息
     * @param relationList 所有主表和附表的关联关系
     * @param tableColumns 所有表字段
     */
    private void packRelationAndInsertToRedis(List<GenTable> tableList, List<GenTableRelation> relationList
            , List<GenTableColumn> tableColumns) {
        for (GenTable table : tableList) {
            List<GenTable> tableListTemp = new ArrayList<>(16);
            //对关联关系表进行排序
            relationList = relationList.stream().sorted(Comparator.comparing(GenTableRelation::getRelationParentId).thenComparing(GenTableRelation::getSort)).collect(Collectors.toList());

            for (GenTableRelation relation : relationList) {
                if (relation.getRelationParentId().equals(table.getTableId())) {
                    //关联主表PK gen_table_column的id
                    Long childId = relation.getRelationChildId();
                    //根据gen_table_column的id查询出表id
                    GenTableColumn genTableColumn = genTableColumnService.selectGenTableColumnListByColumnId(childId);
                    // TODO: 2021/4/8
                    //从tableList中去取出对应表的对象
                    if (genTableColumn != null) {
                        List<GenTable> collect = tableList.stream()
                                .filter(genTable -> genTable.getTableId().equals(genTableColumn.getTableId()))
                                .collect(Collectors.toList());
                        GenTable genTable = collect.get(0);
                        List<GenTableColumn> collectColumn = tableColumns.stream()
                                .filter(genTableColumns -> genTableColumns.getTableId().equals(genTableColumn.getTableId()))
                                .collect(Collectors.toList());
                        genTable.setColumns(collectColumn);
                        tableListTemp.add(genTable);
                    }
                }
            }
            table.setRelationList(tableListTemp);
            redisService.setCacheObject(RedisKey.RELATION + table.getTableName(), table, 12L, TimeUnit.DAYS);
        }
    }

    /**
     * 功能描述: 把table中塞入对应的column， 同时把所有的信息塞到redis中
     *
     * @param tableList       tableList
     * @param genTableColumns 所有的列
     */
    private void packTableAndInsertToRedis(List<GenTable> tableList, List<GenTableColumn> genTableColumns) {
        for (GenTable table : tableList) {
            List<GenTableColumn> columnList = new ArrayList<>(16);
            for (GenTableColumn tableColumn : genTableColumns) {
                if (table.getTableId().equals(tableColumn.getTableId())) {
                    tableColumn.setTableName(table.getTableName());
                    columnList.add(tableColumn);
                }
            }

            table.setColumns(columnList);
            redisService.setCacheObject(RedisKey.TABLE_INFO + table.getTableName(), table, 12L, TimeUnit.DAYS);
        }
    }


    /**
     * 手动更新redis缓存表数据
     *
     * @Description
     * @author tjf
     * @Date 2021/3/29
     */
    public AjaxResult updateRedisTable() {
        //获取所有的表和表字段,更新到redis中
        List<GenTable> tableList = genTableService.selectGenTableList(new GenTable());
        if (null == tableList || tableList.isEmpty()) {
            return AjaxResult.error("当前没有可更新数据");
        }
        List<Long> tableIdList = tableList.stream().map(GenTable::getTableId).collect(Collectors.toList());
        List<GenTableColumn> genTableColumns = genTableColumnService.listByTableIdList(tableIdList);
        if (null == genTableColumns || genTableColumns.isEmpty()) {
            return AjaxResult.error("当前没有可更新数据");
        }
        packTableAndInsertToRedis(tableList, genTableColumns);
        return AjaxResult.success();
    }
}
