package cn.com.capcloud.api;

import cn.com.capcloud.api.action.service.ApiDao;
import cn.com.capcloud.api.action.service.ApiService;
import cn.com.capcloud.ccui.core.common.json.JackJSON;
import cn.com.capcloud.ccui.core.common.json.JackJSONObject;
import cn.com.capcloud.core.cache.BaseConfigStaticCache;
import cn.com.capcloud.core.system.security.JwtTokenProvider;
import cn.com.capcloud.core.util.ReadProperty;
import cn.com.capcloud.api.action.ApiAction;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@CrossOrigin//支持跨域请求
@RestController
@RequestMapping("/api")
public class ApiController {

    @Resource
    private ReadProperty readProperty;
    @Resource
    private ApiService apiService;
    @Resource
    private ApiAction apiAction;
    @Resource
    private JwtTokenProvider jwtTokenProvider;

    @RequestMapping("/data/myAction")
    @ResponseBody
    public KHCResponseEntity myAction(@RequestBody String jsonStr, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        String retStr= null;
        try {
            retStr = apiAction.myAction(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        apiService.apiLogSave(jsonStr,request,khcResponseEntity,startTime);
        return khcResponseEntity;
    }
    @RequestMapping("/data/page")
    @ResponseBody
    public KHCResponseEntity page(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.page(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/list")
    @ResponseBody
    public KHCResponseEntity list(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.list(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/showAll")
    @ResponseBody
    public KHCResponseEntity showAll(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.showAll(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/findOne")
    @ResponseBody
    public KHCResponseEntity findOne(@RequestBody String jsonStr, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        String retStr= null;
        try {
            retStr = apiAction.findOne(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        apiService.apiLogSave(jsonStr,request,khcResponseEntity,startTime);
        return khcResponseEntity;
    }
    @RequestMapping("/data/save")
    @ResponseBody
    public KHCResponseEntity save(@RequestBody String jsonStr, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        String retStr= null;
        try {
            retStr = apiAction.save(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        apiService.apiLogSave(jsonStr,request,khcResponseEntity,startTime);
        return khcResponseEntity;
    }
    //插入一条空数据
    @RequestMapping("/data/insertOne")
    @ResponseBody
    public KHCResponseEntity insertOne(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.insertOne(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/del")
    @ResponseBody
    public KHCResponseEntity del(@RequestBody String jsonStr, HttpServletRequest request) {
        long startTime = System.currentTimeMillis();
        String retStr= null;
        try {
            retStr = apiAction.del(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        apiService.apiLogSave(jsonStr,request,khcResponseEntity,startTime);
        return khcResponseEntity;
    }
    @RequestMapping("/data/showAllForTree")
    @ResponseBody
    public KHCResponseEntity showAllForTree(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr=apiAction.showAllForTree(jsonStr,request);
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/login")
    @ResponseBody
    public KHCResponseEntity login(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.login(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/importExcelDataNew")
    @ResponseBody
    public KHCResponseEntity importExcelDataNew(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.importExcelDataNew(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/importJsonData")
    @ResponseBody
    public KHCResponseEntity importJsonData(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.importJsonData(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/updateJsonData")
    @ResponseBody
    public KHCResponseEntity updateJsonData(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.updateJsonData(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/exportWordData")
    @ResponseBody
    public KHCResponseEntity exportWordData(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.exportWordData(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/exportExcelData")
    @ResponseBody
    public KHCResponseEntity exportExcelData(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.exportExcelData(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/exportExcelOneData")
    @ResponseBody
    public KHCResponseEntity exportExcelOneData(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.exportExcelOneData(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/exportExcelTemplate")
    @ResponseBody
    public KHCResponseEntity exportExcelTemplate(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.exportExcelTemplate(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/data/createOnePdf")
    @ResponseBody
    public KHCResponseEntity createOnePdf(@RequestBody String jsonStr, HttpServletRequest request) {
        String retStr= null;
        try {
            retStr = apiAction.createOnePdf(jsonStr,request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }
    @RequestMapping("/file/upload")
    @ResponseBody
    public KHCResponseEntity upload(HttpServletRequest request) {
        String retStr=apiAction.upload(request);
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(retStr, KHCResponseEntity.class);
        return khcResponseEntity;
    }

    /**
     *
     * @param request
     * @param response
     * 文件上传服务器的可走这个接口下载，其他上传非服务器的直接走第三方下载地址即可（如阿里云或minio等）
     * @throws IOException
     */
    @RequestMapping("/file/downFile")
    public void downFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileDiskName = request.getParameter("fileDiskName");
        String realFileName=request.getParameter("realFileName");
        String suffix = request.getParameter("suffix");
        if (suffix != null && suffix.length() > 1) {
            suffix = suffix.substring(1, suffix.length());
        }
        String fileDir=readProperty.getUploadFilePath();
        if(ApiDao.isInvalidPath(fileDiskName)){
            throw new Exception("非法文件路径，禁止下载！");
        }
        File file = new File(fileDir + fileDiskName);
        if (!file.exists()) {
            throw new Exception("文件不存在："+realFileName);
        }
        FileInputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        inputStream.read(data);
        inputStream.close();
        apiService.setContentType(response,suffix);
        String downloadFileName = request.getParameter("downFileName");
        if (downloadFileName == null || downloadFileName.length() == 0) {
            downloadFileName = realFileName;
        }
        response.addHeader("Content-Disposition",
                "attachment; filename=" + URLEncoder.encode(downloadFileName, "utf-8"));
        OutputStream stream = response.getOutputStream();
        stream.write(data);
        stream.flush();
        stream.close();
    }

    /**
     * 检查是否有token再返回一些重要的资源
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/data/checkAcl")
    public ResponseEntity<String> checkAcl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Cookie[] cookies = request.getCookies();
        String frontPath= String.valueOf(BaseConfigStaticCache.get("system.settings.context.front.path"));
        if(!frontPath.equals("none")){
            frontPath=frontPath+"-";
        }
        boolean isLogin=false;
        if(cookies!=null&&cookies.length>0) {
            for (int i = 0; i < cookies.length; i++) {
                String key=cookies[i].getName();
                if (key.equals(frontPath+"token")) {
                    String token=cookies[i].getValue();
                    try {
                        isLogin=jwtTokenProvider.validateToken(token);
                    } catch (Exception e) {
                    }
                }
            }
        }
        if(isLogin) {
            System.out.println("有效token");
            return new ResponseEntity<>("get front res success", HttpStatus.OK);
        }else {
            System.out.println("无效token，或没有token");
            return new ResponseEntity<>("get front res error,please login system", HttpStatus.UNAUTHORIZED);
        }

    }

    /**
     * 心跳接口
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/data/health")
    @ResponseBody
    public KHCResponseEntity health(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> retMap=apiService.getReturnDataByCode("ok");
        retMap.put("message","服务正在运行");
        String str= JackJSONObject.fromObject(retMap).toString();
        KHCResponseEntity khcResponseEntity = JackJSON.parseObject(str,KHCResponseEntity.class);
        return khcResponseEntity;
    }

}
