package com.tykj.model.controller;



import com.tykj.base.result.ApiException;
import com.tykj.base.result.ResultUtil;

import com.tykj.model.dao.QuoteDao;
import com.tykj.model.dao.RuleDao;

import com.tykj.model.entity.ColumnInfo;
import com.tykj.model.entity.Quote;
import com.tykj.model.entity.Rule;
import com.tykj.model.entity.TableInfo;

import com.tykj.model.entity.vo.*;

import com.tykj.model.service.ModelService;
import com.tykj.model.service.impl.ModelHelper;
import com.tykj.model.utils.SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.hibernate.internal.SessionImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.*;

/**
 * @ClassName ModelController
 * @Description TODO
 * @Author WWW
 * @Date 2021/2/26 13:35
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/model")
@Api(tags = "数据模型层接口")
public class ModelController {

    @Autowired
    private ModelService modelService;

    @Autowired
    private ModelHelper modelHelper;
    @Autowired
    private QuoteDao quoteDao;
    @Autowired
    private RuleDao ruleDao;
    @Autowired
    SessionUtil sessionUtil;
    @Autowired
    private Environment env;

    /**
     * @param
     * @return java.util.List<com.tykj.workflowcore.model_layer.model.TableInfo>
     * @Author WWW
     * @Description 得到所有数据库信息
     * @Date 16:19 2021/3/4
     **/
    @ApiOperation("得到所有数据表信息")
    @PostMapping("/getAllEntity")
    public ResponseEntity getAllEntity(@RequestBody SearchTableInfoVo searchTableInfoVo) {
        Page<TableInfo> tableInfos = modelService.pageAllEntities(searchTableInfoVo);
        return ResultUtil.success(tableInfos, "数据查询成功！");
    }
    /**
     * @return org.springframework.http.ResponseEntity
     * @Author WWW
     * @Description 根据表名查询所有数据
     * @Date 9:30 2021/3/11
     **/
    @ApiOperation("根据表名查询所有数据")
    @PostMapping("/getAll")
    public ResponseEntity getAll(@RequestBody SearchAllVO searchAllVO) throws SQLException {
        if (searchAllVO.getOrderConditions() != null && searchAllVO.getOrderConditions().size() > 0) {
            return ResultUtil.success(modelService.findAllByName(searchAllVO.getTableName(), searchAllVO.getOrderConditions()), "查询成功！");
        }
        return ResultUtil.success(modelService.findAllByName(searchAllVO.getTableName()), "查询成功！");
    }
    /**
     * @param searchColumnInfoVo
     * @return java.util.List<com.tykj.workflowcore.model_layer.model.ColumnInfo>
     * @Author WWW
     * @Description 根据表名得到所有字段名
     * @Date 16:20 2021/3/4
     **/
    @ApiOperation("根据表名或者id查询表中所有字段")
    @PostMapping("/getAllField")
    public ResponseEntity getFields(@RequestBody SearchColumnInfoVo searchColumnInfoVo) {
        List<ColumnInfo> columnInfos = modelService.showModelFields(searchColumnInfoVo);
//        if ("com.mysql.cj.jdbc.Driver".equals(env.getProperty("spring.datasource.driver-class-name"))
//                || "com.mysql.jdbc.Driver".equals(env.getProperty("spring.datasource.driver-class-name"))) {
//            for (ColumnInfo columnInfo : columnInfos) {
//                if (columnInfo.getFieldName().equals("ID"))
//                {
//                    continue;
//                }
//                columnInfo.setFieldName(columnInfo.getFieldName().toLowerCase());
//                System.out.println(columnInfo);
//            }
//        }
        for (ColumnInfo columnInfo : columnInfos) {
            List<Quote> allQuote = quoteDao.findAllByColumnId(columnInfo.getId());
            Rule rule;
            try {
                rule = ruleDao.findAllByColumnId(columnInfo.getId());
            } catch (Exception e) {
                throw new ApiException("规则不唯一！");
            }
            columnInfo.setRule(rule);
            columnInfo.setQuoteList(allQuote);
        }
        return ResultUtil.success(columnInfos, "数据查询成功！");
    }

    /**
     * @param
     * @return org.springframework.http.ResponseEntity
     * @Author WWW
     * @Description 新增数据模型
     * @Date 16:21 2021/3/4
     **/
    @ApiOperation("新增数据模型")
    @PostMapping(value = "/addModel")
    public ResponseEntity addModel(@RequestBody TableVO tableVO) {

        long start = System.currentTimeMillis();
        TableInfo tableInfo = modelService.newTable(tableVO);
        long end = System.currentTimeMillis();
        log.warn("创建总用时为：{}秒", (end - start) / 1000.0);
        return ResultUtil.success(tableInfo, "新建成功!");
    }

    /**
     * @param map
     * @return int
     * @Author WWW
     * @Description 对应表插入数据
     * map （表名，字段数据）
     * @Date 16:22 2021/3/4
     **/
    @ApiOperation(value = "根据表名表插入数据")
    @PostMapping("/insertValues")
    public ResponseEntity insertValues(@RequestBody Map<String, Object> map) {
        SessionImpl session =(SessionImpl) sessionUtil.getSession();
        int i = modelService.operationValueByEntityName(map,session,session::saveOrUpdate,modelService::validationAllRuleAndQuote);
        if (i == 0) {
            return ResultUtil.success("", "数据插入成功！");
        }
        return ResultUtil.failed("模型类型不支持插入数据！");
    }

    /**
     * @param mapList
     * @return int
     * @Author WWW
     * @Description 对应表插入数据
     * map （表名，字段数据）
     * @Date 16:22 2021/3/4
     **/
    @ApiOperation(value = "根据表名表插入数据")
    @PostMapping("/insertValueList")
    public ResponseEntity insertValueList(@RequestBody List<Map<String, Object>> mapList) {
        SessionImpl session =(SessionImpl) sessionUtil.getSession();
        int i = modelService.operationValueByEntityNameList(mapList,session,session::saveOrUpdate,modelService::validationAllRuleAndQuote);
        if (i == 0) {
            return ResultUtil.success("", "数据保存成功！");
        }
        return ResultUtil.failed("模型类型不支持插入数据！");
    }


    /**
     * @param cqv
     * @return 复杂查询
     */
    @ApiOperation("复杂查询")
    @PostMapping("/complexQuery")
    public ResponseEntity complexQuery(@RequestBody complexQueryVo cqv) {
        List list = modelService.complexQuery(cqv.getTableName(),
                cqv.getColumnNames(),
                cqv.getQueryConditions(),
                cqv.getGroupByColumn());
        if (list != null) {
            return ResultUtil.success(list, "查询成功!");
        }
        return ResultUtil.failed(null, "没有数据!");
    }

    /**
     * @param cqv
     * @return 复杂查询
     */
    @ApiOperation("复杂查询(分类)")
    @PostMapping("/complexQuery/group")
    public ResponseEntity complexQueryWithGroup(@RequestBody complexQueryVo cqv) {
      CustomPage customPage = modelService.complexQueryWithGroup(cqv.getTableName(), cqv.getGroupCondition(), cqv.getColumnNames(), cqv.getQueryConditions(), cqv.getGroupByColumn(), cqv.getPage(), cqv.getSize());
        if (customPage.getContents() != null) {
            return ResultUtil.success(customPage, "查询成功!");
        }
        return ResultUtil.failed(HttpStatus.INTERNAL_SERVER_ERROR, "没有数据!");
    }

    @ApiOperation("编辑操作")
    @PutMapping("/update")
    public ResponseEntity updateTable(@RequestBody UpdateTableInfoVO updateTableInfoVO) {
        sessionUtil.addXml(modelService.updateTable(updateTableInfoVO));
//        return
//        if (i == 1) {
        return ResultUtil.success("", "修改成功！");
//        }
//        return ResultUtil.failed("业务不支持修改！");
    }

    @ApiOperation("删除操作")
    @DeleteMapping("/delete")
    public ResponseEntity delTable(DelTableVO delTableVO) {

        int i = modelService.delTable(delTableVO);
        if (i == 1) {
            return ResultUtil.success("", "删除成功！");
        }
        return ResultUtil.failed("业务类型不支持删除！");
    }


    @ApiOperation("获得获得非聚合对象example")
    @GetMapping("/example")
    public ResponseEntity getJSONExample(Integer id) {
        return ResultUtil.success(modelHelper.getJsonExample(id),
                "获得example成功！");
    }

    @ApiOperation("自定义SQL查询")
    @PostMapping("/sql")
    public ResponseEntity executeSql(String sql) {
        try {
            return ResultUtil.success(modelService.executeQuery(sql), "查询成功！");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return ResultUtil.failed("SQL错误，查询失败！");
    }

    @ApiOperation("删除接口")
    @PostMapping("/deleteValue")
    public ResponseEntity deleteValue(@RequestBody Map<String, Object> map) {
        SessionImpl session =(SessionImpl) sessionUtil.getSession();
        int i = modelService.operationValueByEntityName(map,session,session::delete,null);
        if (i == 0) {
            return ResultUtil.success("", "数据删除成功！");
        }
        return ResultUtil.failed("数据删除失败！");
    }

    @ApiOperation("字段类型")
    @GetMapping("/type")
    public ResponseEntity type() {
        //这代码狗都不改
        List<ColumnTypeVO> columnTypeVOS = Arrays.asList(
                new ColumnTypeVO("数字", "java.lang.Integer", "11")
                , new ColumnTypeVO("浮点数", "java.lang.Double", "11")
                , new ColumnTypeVO("单/多行文本", "java.lang.String", "255")
                , new ColumnTypeVO("布尔值", "java.lang.Boolean", "1"));
        return ResultUtil.success(columnTypeVOS, "查询成功！");
    }

}
