package com.hchyun.generator.controller;

import com.github.pagehelper.PageHelper;
import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.core.controller.BaseController;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.utils.ServerResult;
import com.hchyun.common.utils.StringUtils;
import com.hchyun.common.utils.sql.SqlUtil;
import com.hchyun.generator.entity.UniCon;
import com.hchyun.generator.entity.UniQuery;
import com.hchyun.generator.service.QueryService;
import com.hchyun.generator.util.MapExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Author 18209
 * Date 2021/1/30 18:25
 * Version 1.0
 */
@RestController
@Api("query")
@RequestMapping("/query")
public class QueryController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(QueryController.class);


    @Autowired
    private QueryService queryService;


    @ApiOperation("获取查询基本信息")
    @PreAuthorize("@ss.hasPermi('query:real:list')")
    @GetMapping("/real/{id}")
    public AjaxResult RealInfo(@PathVariable("id") Long id) {
        try {
            if (id == null) {
                return AjaxResult.error("id不能为空!");
            }
            ServerResult<List<UniCon>> serverResult = queryService.RealInfo(id);
            if (serverResult.isStart()) {
                return AjaxResult.success(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    @PreAuthorize("@ss.hasAnyPermi('query:real:export')")
    @PutMapping("/real/export")
    public AjaxResult exportReal(@Validated @RequestBody UniQuery uniQuery){
        try {
            ServerResult<List<Map<String,Object>>> serverResult = queryService.RealData(uniQuery,1);
            if (serverResult.isStart()){
                return new MapExcelUtil().exportExcel(serverResult.getData(),serverResult.getSheetName());
            }else {
                return AjaxResult.error(serverResult.getMsg());
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }


    @PreAuthorize("@ss.hasAnyPermi('query:real:data')")
    @PutMapping("/real")
    public Serializable RealData(@Validated @RequestBody UniQuery uniQuery) {
        try {
            ServerResult<List<Map<String, Object>>> serverResult = queryService.RealData(uniQuery,2);
            if (serverResult.isStart()) {
                return getDataTable(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }


    @PreAuthorize("@ss.hasPermi('query:list')")
    @GetMapping("/{id}")
    public AjaxResult Info(@PathVariable("id") Long id) {
        try {
            ServerResult<UniQuery> serverResult = queryService.selectQueryById(id);
            if (serverResult.isStart()) {
                UniQuery uniQuery = serverResult.getData();
                Map<String, Object> modeMap = new HashMap<>();
                List<UniCon> uniCons = uniQuery.getUniCons();
                uniQuery.setUniCons(null);
                modeMap.put("info", uniQuery);
                modeMap.put("list", uniCons);
                return AjaxResult.success(modeMap);
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    @PreAuthorize("@ss.hasPermi('query:edit')")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody UniQuery uniQuery) {
        try {
            ServerResult serverResult = queryService.updateQueryInfo(uniQuery);
            if (serverResult.isStart()) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    @PreAuthorize("@ss.hasAnyPermi('query:export')")
    @PutMapping("export")
    public AjaxResult export(@Validated @RequestBody UniQuery uniQuery) {
        try {
            ServerResult<List<Map<String,Object>>> serverResult = queryService.previewQuery(uniQuery);
            if (serverResult.isStart()){
                return new MapExcelUtil().exportExcel(serverResult.getData(),uniQuery.getUqName());
            }else {
                return AjaxResult.error(serverResult.getMsg());
            }
        }catch (RuntimeException e){
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    @PreAuthorize("@ss.hasPermi('query:preview')")
    @PutMapping("preview")
    public Serializable Preview(@Validated @RequestBody UniQuery uniQuery) {
        try {
            startPage(uniQuery);
            ServerResult<List<Map<String, Object>>> serverResult = queryService.previewQuery(uniQuery);
            if (serverResult.isStart()) {
                return getDataTable(serverResult.getData());
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    @PutMapping("/release")
    public AjaxResult Release(@RequestBody UniQuery uniQuery) {
        try {
            if (uniQuery.getId() == null) {
                return AjaxResult.error("id不能为空!");
            } else {
                if (uniQuery.getIsRelease() == 1 || uniQuery.getIsRelease() == 2) {
                    ServerResult<Integer> serverResult = queryService.Release(uniQuery);
                    if (serverResult.isStart()){
                        return AjaxResult.success();
                    }else {
                        return AjaxResult.error(serverResult.getMsg());
                    }
                } else {
                    return AjaxResult.error("状态输入错误!");
                }
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage(UniQuery uniQuery) {
        Integer pageNum = uniQuery.getPageNum();
        Integer pageSize = uniQuery.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql("");
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }
}
