package com.keyware.shandan.browser.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keyware.shandan.bianmu.entity.MetadataBasicVo;
import com.keyware.shandan.bianmu.service.DirPermissionService;
import com.keyware.shandan.bianmu.service.MetadataService;
import com.keyware.shandan.common.enums.SystemTypes;
import com.keyware.shandan.common.util.RsaUtil;
import com.keyware.shandan.common.util.StringUtils;
import com.keyware.shandan.datasource.entity.DBTableColumnVo;
import com.keyware.shandan.frame.config.security.SecurityUtil;
import com.keyware.shandan.system.entity.SysSetting;
import com.keyware.shandan.system.entity.SysUser;
import com.keyware.shandan.system.service.SysTheadConfigService;
import com.keyware.shandan.system.service.SysUserService;
import com.keyware.shandan.system.utils.SysSettingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 首页 前端控制器
 * </p>
 *
 * @author GuoXin
 * @since 2021/6/17
 */
@RestController
@RequestMapping("/")
public class BrowserIndexController {

    @Autowired
    private MetadataService metadataService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DirPermissionService permissionService;

    @Autowired
    private SysTheadConfigService theadConfigService;

    @Value("${project.cors-lib-search:#}")
    private String corsLibSearchUrl;

    /**
     * 首页路由
     *
     * @param modelAndView
     * @return
     */
    @GetMapping("/index")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("index");
        permissionService.refreshCache();
        modelAndView.addObject("appName", SysSettingUtil.getCurrentSysSetting().getSysName());
        //登录用户
        SysUser user = sysUserService.findByLoginName(SecurityUtil.getLoginUserByContext().getUsername());
        if (user != null) {
            user.setPassword(null);
            modelAndView.addObject("loginUser", user);
            modelAndView.addObject("user", user);
        }
        //系统信息
        modelAndView.addObject("sys", SysSettingUtil.getCurrentSysSetting());
        //后端公钥
        String publicKey = RsaUtil.getPublicKey();
        modelAndView.addObject("publicKey", publicKey);

        SysSetting bianmuSetting = SysSettingUtil.getSysSetting(SystemTypes.BIANMU.name());
        SysSetting dbtoolSetting = SysSettingUtil.getSysSetting(SystemTypes.DBTOOL.name());
        modelAndView.addObject("bianmuServer", bianmuSetting.getSysAddress());
        modelAndView.addObject("dbtoolAddress", dbtoolSetting.getSysAddress());
        modelAndView.addObject("corsLibSearchUrl", corsLibSearchUrl);
        return modelAndView;
    }

    @GetMapping("/browser")
    public ModelAndView browser(ModelAndView mov, Authentication auth) {
        mov.setViewName("browser");
        SysSetting bianmuSetting = SysSettingUtil.getSysSetting(SystemTypes.BIANMU.name());
        mov.addObject("bianmuServer", bianmuSetting.getSysAddress());
        mov.addObject("theadConfig", theadConfigService.listByCreateUser(auth.getName()));
        return mov;
    }


    /**
     * 跳转数据资源搜索页面
     *
     * @param mov    视图模型
     * @param metaId 数据资源ID
     * @return 视图模型
     */
    @GetMapping("/search/meta/{metaId}")
    public ModelAndView metaSearch(ModelAndView mov, @PathVariable String metaId) {
        mov.setViewName("meta_search");
        MetadataBasicVo meta = null;
        List<DBTableColumnVo> columnVoList = new ArrayList<>();
        if (StringUtils.isNotBlank(metaId)) {
            meta = metadataService.get(metaId).getData();
            // 查询字段列
            meta.getMetadataDetailsList().forEach(list -> columnVoList.addAll(list.getColumnList()));
        }
        mov.addObject("metadata", meta);
        mov.addObject("columns", columnVoList);
        return mov;
    }

    /**
     * 生成树的json对象
     *
     * @param vo
     * @param type
     * @param last
     * @return
     */
    private JSONObject treeJson(Object vo, String type, Boolean last) {
        JSONObject json = new JSONObject();
        json.put("type", type);
        json.put("spread", false);
        json.put("last", last);
        json.put("basicData", JSON.toJSON(vo));
        json.put("children", new ArrayList<>());
        return json;
    }
}
