package com.hchyun.generator.controller;

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


import com.hchyun.common.constant.ReturnConstants;
import com.hchyun.common.core.controller.HcyBaseController;
import com.hchyun.common.utils.ServerResult;
import com.hchyun.generator.dto.InterTableDto;
import com.hchyun.generator.entity.Apiclass;
import com.hchyun.generator.service.ApiclassService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hchyun.common.annotation.Log;
import com.hchyun.common.core.entity.AjaxResult;
import com.hchyun.common.enums.BusinessType;
import com.hchyun.generator.entity.InterTable;
import com.hchyun.generator.service.InterTableService;
import com.hchyun.common.utils.poi.ExcelUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * 接口信息Controller
 *
 * @author hchyun
 * @date 2021-01-25
 */

@Api("接口信息")
@RestController
@RequestMapping("/generator/intertable")
public class InterTableController extends HcyBaseController {
    protected final Logger logger = LoggerFactory.getLogger(InterTableController.class);

    @Autowired
    private InterTableService interTableService;
    @Autowired
    private ApiclassService apiclassService;

    /**
     * 查询接口信息列表
     */
    @PreAuthorize("@ss.hasPermi('generator:intertable:list')")
    @GetMapping("/list")
    public Serializable list(InterTable interTable) {
        try {
            ServerResult<Map<String, Object>> serverResult = interTableService.selectInterTableList(interTable);
            if (serverResult.isStart()) {
                return AjaxResult.success(serverResult.getData());
            } else {
                return AjaxResult.info(serverResult.getMsg());
            }
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 预览代码(工作流)
     */

    @ApiOperation("预览代码(工作流)")
    @PreAuthorize("@ss.hasPermi('generator:intertable:classpreview')")
    @Log(title = "预览代码(工作流)", businessType = BusinessType.GENCODE)
    @GetMapping("/classpreview/{id}")
    public AjaxResult classPreview(@PathVariable("id") Long id) {
        try {
            ServerResult<Map<String, String>> serverResult = interTableService.previewCodeCalss(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);
        }
    }

    /**
     * 预览代码(工作台)
     */
    @ApiOperation("预览代码(工作台)")
    @PreAuthorize("@ss.hasPermi('generator:intertable:modulepreview')")
    @Log(title = "预览代码(工作台)", businessType = BusinessType.GENCODE)
    @GetMapping("/modulepreview/{id}")
    public AjaxResult modulePreview(@PathVariable("id") Long id) {
        try {
            ServerResult<Map<String, Object>> serverResult = interTableService.previewCodeMoudle(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);
        }
    }


    /**
     * 生成代码(工作流)
     *
     * @param id
     * @return
     */
    @ApiOperation("生成代码(工作流)")
    @PreAuthorize("@ss.hasPermi('generator:intertable:classgen')")
    @Log(title = "生成代码(工作流)", businessType = BusinessType.GENCODE)
    @GetMapping("/classgen/{id}")
    public AjaxResult classGenerator(@PathVariable("id") Long id, HttpServletResponse response) {
        try {
            ServerResult<byte[]> serverResult = interTableService.generatorCodeClass(id);
            if (serverResult.isStart()) {
                genCode(response, serverResult.getData());
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        } catch (RuntimeException | IOException e) {
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }

    /**
     * 生成代码(工作台)
     * @param id
     * @param response
     * @return
     */
    @ApiOperation("生成代码(工作台)")
    @PreAuthorize("@ss.hasPermi('generator:intertable:moudlegen')")
    @Log(title = "生成代码(工作台)", businessType = BusinessType.GENCODE)
    @GetMapping("/moudlegen/{id}")
    public AjaxResult moudleGenerator(@PathVariable("id") Long id, HttpServletResponse response){
        try {
            ServerResult<byte[]> serverResult = interTableService.generatorCodeMoudle(id);
            if (serverResult.isStart()) {
                genCode(response, serverResult.getData());
                return AjaxResult.success();
            } else {
                return AjaxResult.error(serverResult.getMsg());
            }
        }catch (RuntimeException | IOException e){
            logger.error(e.getMessage());
            return AjaxResult.error(ReturnConstants.SYS_ERROR);
        }
    }



    /**
     * 修改接口信息
     */
    @PreAuthorize("@ss.hasPermi('generator:intertable:edit')")
    @Log(title = "接口信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody InterTableDto interTableDto) {
        try {
            ServerResult<Integer> serverResult = interTableService.updateInterTable(interTableDto);
            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);
        }
    }

    /**
     * 生成zip文件
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\"hchyun.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }


//    /**
//     * 导出接口信息列表
//     */
//    @PreAuthorize("@ss.hasPermi('generator:intertable:export')")
//    @Log(title = "接口信息", businessType = BusinessType.EXPORT)
//    @GetMapping("/export")
//    public AjaxResult export(InterTable interTable) {
//        try {
//            ServerResult<List<InterTable>> serverResult = interTableService.selectInterTableList(interTable);
//            ExcelUtil<InterTable> util = new ExcelUtil<InterTable>(InterTable. class);
//            if (serverResult.isStart()) {
//                return util.exportExcel(serverResult.getData(), "intertable");
//            } else {
//                return AjaxResult.error(serverResult.getMsg());
//            }
//        } catch (RuntimeException e) {
//            logger.error(e.getMessage());
//            return AjaxResult.error(ReturnConstants.SYS_ERROR);
//        }
//    }

//    /**
//     * 获取接口信息详细信息
//     */
//    @PreAuthorize("@ss.hasPermi('generator:intertable:query')")
//    @GetMapping(value = "/{id}")
//    public AjaxResult Info(@PathVariable("id") Long id) {
//        try {
//            ServerResult<InterTable> serverResult = interTableService.selectInterTableById(id);
//            if (serverResult.isStart()) {
//                return AjaxResult.success(serverResult.getData());
//            } else {
//                return AjaxResult.info(serverResult.getMsg());
//            }
//        } catch (RuntimeException e) {
//            logger.error(e.getMessage());
//            return AjaxResult.error(ReturnConstants.SYS_ERROR);
//        }
//    }
//
//    /**
//     * 新增接口信息
//     */
//    @PreAuthorize("@ss.hasPermi('generator:intertable:add')")
//    @Log(title = "接口信息", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody InterTable interTable) {
//        try {
//            ServerResult<Integer> serverResult = interTableService.insertInterTable(interTable);
//            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.hasPermi('generator:intertable:remove')")
//    @Log(title = "接口信息", businessType = BusinessType.DELETE)
//    @DeleteMapping("/{ids}")
//    public AjaxResult remove(@PathVariable Long[] ids) {
//        try {
//            if (ids.length<0){
//                return AjaxResult.error("id不能为空!");
//            }
//            ServerResult<Integer> serverResult = interTableService.deleteInterTableByIds(ids);
//            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);
//        }
//    }
}