package com.ozs.kpim.controller.kpiconfig;

import com.ozs.kpim.dto.mdm.KpiListColumnDTO;
import com.ozs.kpim.dto.mdm.MdmInfoColumn;
import com.ozs.kpim.dto.mdm.MdmInfoDatabase;
import com.ozs.kpim.dto.mdm.MdmInfoTable;
import com.ozs.kpim.service.kpiconfig.MdmApi;
import com.ozs.kpim.util.R;
import com.ozs.kpim.util.S;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName KpiConfigManagerRemoteApiController
 * @Desc 调用远程接口
 * @Author jade
 * @Date 2019/2/26
 * @Version 1.0
 */
@RestController
@Api(tags = { "KPI配置管理接口(调用微服务)" })
public class KpiConfigRemoteApiController {

    @Resource
    private MdmApi mdmApi;

    @ApiOperation("元数据库下拉列表查询")
    @GetMapping("/kpim/kpiConfig/listMdmDatabases")
    public R<List<MdmInfoDatabase>> listMdmDatabases() {
        try {
            return new R<>(S.OK, S.getMsg(S.OK),mdmApi.listDatabase(null));
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR,e.getMessage());
        }
    }

    @ApiOperation("元数据表下拉列表查询")
    @ApiImplicitParam(name = "databaseId", value = "数据库ID", required = true, paramType = "query", dataType = "String")
    @GetMapping("/kpim/kpiConfig/listMdmTablesByDatabase")
    public R<List<MdmInfoTable>> listMdmTablesByDatabase(@RequestParam(required = true) String databaseId){
        try {
            if(StringUtils.isEmpty(databaseId)){
                return new R<>(S.OK, S.getMsg(S.OK));
            }
            return new R<>(S.OK, S.getMsg(S.OK),mdmApi.listTableByDatabaseId(databaseId));
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR,e.getMessage());
        }
    }

    @ApiOperation("元数据字段下拉列表查询")
    @ApiImplicitParam(name = "tableId", value = "表ID", required = true, paramType = "query", dataType = "String")
    @GetMapping("/kpim/kpiConfig/listMdmColumnsByTable")
    public R<List<MdmInfoColumn>> listMdmColumnsByTable(@RequestParam(required = true) String tableId){
        try {
            if(StringUtils.isEmpty(tableId)){
                return new R<>(S.OK, S.getMsg(S.OK));
            }
            List<MdmInfoColumn> mdmInfoColumns = mdmApi.listColumnByTableId(tableId)
            .stream().map(e->{
                MdmInfoColumn vo = new MdmInfoColumn();
                BeanUtils.copyProperties(e,vo);
                String columnNameShow = e.getColumnCode()+"("+e.getColumnName()+")";
                vo.setColumnNameShow(columnNameShow);
                setRuleInfo(vo);
                return vo;
            }).collect(Collectors.toList());
            return new R<>(S.OK, S.getMsg(S.OK),mdmInfoColumns);
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR,e.getMessage());
        }
    }

    /* *
     * @Author jade
     * @Description 数据类型方法设置
     * 由于目前没有通过字典表建立连接，因此只能再程序中硬拼起来
     * @Date 2019/4/4
     * @Param [record]
     * @return void
    **/
    public void setRuleInfo(MdmInfoColumn record){
        String columnTypeName = record.getColumnTypeName();
        Integer ifChar = record.getIfChar();
        Integer numericScale = record.getNumericScale();
        Integer isFloatPoint = record.getIsFloatPoint();
        Integer isTime = record.getIsTime();
        if(StringUtils.isEmpty(columnTypeName)){
            return;
        }

        // 1.float double 类型
        if(1== isFloatPoint){
            setNumberRule(record,numericScale);

        // 2.时间类型
        }else if(1==isTime){
            setTimeRule(record);

        // 3.其他默认都是文本类型 不直接判断ifChar了
        }else{
            if(columnTypeName.contains("INT")){
                setNumberRule(record,numericScale);
                return;
            }
            setTextRule(record);
        }

    }

    /* *
     * @Author jade
     * @Description 设置文本类型
     * @Date 2019/4/4
     * @Param [record]
     * @return void
    **/
    private void setTextRule(MdmInfoColumn record) {
        record.setRuleType("text");
        record.setRuleFormat("文本");
        record.setRuleTypeDesc("文本");
    }

    /* *
     * @Author jade
     * @Description 设置文本类型
     * @Date 2019/4/4
     * @Param [record]
     * @return void
     **/
    private void setNumberRule(MdmInfoColumn record,Integer number) {
        record.setRuleType("number");
        record.setRuleFormat(""+number);

        if(0==number || null == number){
            record.setRuleTypeDesc("数字(整数)");
        }else{
            record.setRuleTypeDesc("数字(保留"+number+"位小数)");
        }
    }

    /* *
     * @Author jade
     * @Description 时间类型规则，时间直接给个默认值
     * @Date 2019/4/4
     * @Param [record, number]
     * @return void
    **/
    private void setTimeRule(MdmInfoColumn record) {
        record.setRuleType("time");
        record.setRuleFormat("yyyy-MM-dd HH:mm:ss");
        record.setRuleTypeDesc("时间(yyyy-MM-dd HH:mm:ss)");
    }

    @ApiOperation("元数据字段分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "databaseId", value = "数据库ID", required = false, paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "tableId", value = "表ID", required = false, paramType = "query", dataType = "Integer"),
        @ApiImplicitParam(name = "sort", value = "排序字段", required = false, paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "order", value = "排序", required = false, paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "String"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, paramType = "query", dataType = "String")
    })
    @GetMapping("/kpim/kpiConfig/listMdmColumnsWithPages")
    public Object listMdmColumnsWithPages(
        @RequestParam(required = false) String databaseId,
        @RequestParam(required = false) String tableId,
        @RequestParam(required = false,defaultValue = "update_time") String sort,
        @RequestParam(required = false,defaultValue = "desc") String order,
        @RequestParam(required = false,defaultValue = "1") Integer page,
        @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        try {
            return mdmApi.listColumn(null,databaseId,tableId,page,sort,order,pageSize);
        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR,e.getMessage());
        }
    }



    @ApiOperation("根据DatabaseId查询字段列表，按照表进行分组")
    @ApiImplicitParam(name = "databaseId", value = "databaseId", required = true, paramType = "query", dataType = "String")
    @GetMapping("/kpim/kpiConfig/listMdmColumnsGroupByTable")
    public R<List<Map<String, Object>>> listMdmColumnsGroupByTable(@RequestParam(required = true) String databaseId) {
        try {

            List<Map<String, Object>>  result = new ArrayList<>();

            List<KpiListColumnDTO> list = mdmApi.listColumnByDatabaseId(databaseId,null);
            if(list == null || list.size()==0)
                return new R<>(S.OK, S.getMsg(S.OK),result);

            Map<String, List<KpiListColumnDTO>> mdmInfoColumns =
                list.stream().map(e -> {
                    KpiListColumnDTO vo = new KpiListColumnDTO();
                    BeanUtils.copyProperties(e, vo);
                    String columnNameShow = e.getColumnCode() + "(" + e.getColumnName() + ")";
                    vo.setColumnNameShow(columnNameShow);
                    return vo;
                }).collect(Collectors.groupingBy(KpiListColumnDTO::getTableId));

            for (String tableId: mdmInfoColumns.keySet()) {
                Map<String, Object> map = new HashMap<>();
                map.put("tableId",tableId);
                map.put("columns",mdmInfoColumns.get(tableId));
                result.add(map);
            }
            return new R<>(S.OK, S.getMsg(S.OK), result);

        } catch (Exception e) {
            e.printStackTrace();
            return new R<>(S.ERROR, e.getMessage());
        }
    }


}
