package com.keyware.shandan.bianmu.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keyware.shandan.bianmu.entity.DirectoryResource;
import com.keyware.shandan.bianmu.entity.DirectoryVo;
import com.keyware.shandan.bianmu.entity.MetadataBasicVo;
import com.keyware.shandan.bianmu.service.*;
import com.keyware.shandan.common.entity.Result;
import com.keyware.shandan.common.util.StreamUtil;
import com.keyware.shandan.common.util.StringUtils;
import com.keyware.shandan.datasource.entity.DBTableColumnVo;
import com.keyware.shandan.datasource.entity.DataSourceVo;
import com.keyware.shandan.datasource.service.DataSourceService;
import com.keyware.shandan.system.constants.FormTypeEnum;
import com.keyware.shandan.system.entity.SysFormConfig;
import com.keyware.shandan.system.service.SysFormConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
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.text.Collator;
import java.util.*;

/**
 * BianmuCommonController
 *
 * @author Administrator
 * @since 2021/12/15
 */
@RestController
@RequestMapping("/business/metadata")
public class MetadataCommonController {

    @Autowired
    private MetadataService metadataService;

    @Autowired
    private DataSourceService dataSourceService;

    @Autowired
    private DirectoryService directoryService;

    @Autowired
    private DirectoryTreeService treeService;

    @Autowired
    private LabelEntityService labelEntityService;

    @Autowired
    private DataLabelsService labelsService;

    @Autowired
    private SysFormConfigService formConfigService;

    /**
     * 数据资源详细信息页面
     *
     * @param mav
     * @param id
     * @return
     */
    @GetMapping("/details/{id}")
    public ModelAndView metadataDetails(ModelAndView mav, @PathVariable String id) {
        mav.setViewName("business/metadata/details");
        MetadataBasicVo metadata = metadataService.get(id).getData();
        mav.addObject("detailsData", metadata);

        // 查询字段列
        List<DBTableColumnVo> columnVoList = new ArrayList<>();
        metadata.getMetadataDetailsList().forEach(list -> columnVoList.addAll(list.getColumnList()));
        mav.addObject("columnList", columnVoList);

        // 查询示例数据
        DataSourceVo dataSourceVo = dataSourceService.getById(metadata.getDataSourceId());
        Page<HashMap<String, Object>> exampleData = metadataService.getExampleData(metadata, dataSourceVo);
        mav.addObject("exampleList", exampleData.getRecords());

        mav.addObject("LabelConfigSet", labelsService.formConfigList());

        mav.addObject("metadataFormConfig", formConfigService.listByFormType(FormTypeEnum.metadataEditForm));
        return mav;
    }


    /**
     * 示例数据
     *
     * @param metadataId
     * @return
     */
    @GetMapping("/example/data")
    public Result<Page<HashMap<String, Object>>> exampleData(String metadataId) {
        MetadataBasicVo metadata = metadataService.get(metadataId).getData();
        DataSourceVo dataSource = dataSourceService.getById(metadata.getDataSourceId());
        Page<HashMap<String, Object>> result = metadataService.getExampleData(metadata, dataSource);
        return Result.of(result);
    }

    /**
     * 查询数据资源表字段列表
     *
     * @param id
     * @return
     */
    @GetMapping("/columns")
    public Result<JSONArray> columns(String id) {
        return Result.of(metadataService.getColumns(id));
    }

    /**
     * 根据目录ID查询数据资源列表
     *
     * @param directoryId
     * @return
     */
    @GetMapping("/list/directory")
    @Transactional(readOnly = true)
    public Result<Page<DirectoryResource>> listByDirectory(Page<DirectoryResource> page, String directoryId, String resourceName, boolean allChild,String reviewStatus) {
        if (StringUtils.isBlank(directoryId)) {
            return Result.of(null, false, "参数不能为空");
        }
        Page<DirectoryResource> result = treeService.resourcePage(page, directoryId, resourceName, allChild,reviewStatus);
        StreamUtil.as(result.getRecords()).peek(item -> {
            if (StringUtils.hasText(item.getDirectoryPath())) {
                int i = item.getDirectoryPath().lastIndexOf("/");
                if (i > 0) {
                    item.setDirectoryPath(item.getDirectoryPath().substring(0, i));
                }
            }
            item.setHasMark(labelEntityService.getById(item.getId()) != null);
        }).toList();

        //定义中文排序器
        Comparator<Object> chinese = Collator.getInstance(Locale.CHINA);
        result.getRecords().sort((a, b) -> chinese.compare(a.getDirectoryPath(), b.getDirectoryPath()));
        return Result.of(result);
    }
}
