package com.controller;

import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.log.Log;
import com.jfinal.upload.UploadFile;
import com.model.Book;
import com.model.BookDetail;
import com.model.BookPlus;
import com.service.BookService;
import com.tools.JwtUtils;
import com.validator.BookValidator;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@ControllerInterface(path="/file")
public class FileController extends BaseController {

    Log log =Log.getLog(this.getClass().getName());

    public void index() {
        render("/filedemo.html");
    }

    java.text.SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    static String file_ext_str = ".xls,.xlsx,.doc,.docx,.pdf,.jpg,.png,.gif,.jpeg,.iso";

    public void uploadImage(){
        try{
            UploadFile file =getFile();

            String filename = file.getFileName();
            String ext = filename.substring(filename.lastIndexOf("."));
            if(file_ext_str.indexOf(ext) == -1){
                fail(1,"文件格式不正确，支持的文件类型为："+file_ext_str);
                return;
            }
            Map<String,String> map = new HashMap<String,String>();

            Map info = JwtUtils.validateJWTForMap(this.getPara("token"));
            if(info == null){
                fail_token();
                return;
            }
            int orgid = (int)info.get("orgid");
            String dirpath = orgid +"/"+info.get("userid")+"/"+sf.format(new Date());
            String path ="/"+dirpath + "/" + file.getFileName();
            File targetFile =new File(getRequest().getRealPath("upload")+path);
            if (targetFile.exists()){
                FileUtils.forceDelete(targetFile);
            }
            FileUtils.moveFile(file.getFile(), targetFile);
            map.put("src", "/"+"upload"+ path);
            map.put("title",file.getFileName());
            success(200,"调用成功",map);
        }catch (Exception e) {
            fail();
        }
    }

    public void layuiUploadImage(){
        try{
            UploadFile file =getFile();
            String filename = file.getFileName();
            String ext = filename.substring(filename.lastIndexOf("."));
            if(file_ext_str.indexOf(ext) == -1){
                fail(1,"文件格式不正确，支持的文件类型为："+file_ext_str);
                return;
            }
            Map<String,String> map = new HashMap<String,String>();

            Map info = JwtUtils.validateJWTForMap(this.getPara("token"));
            if(info == null){
                fail_token();
                return;
            }
            int orgid = (int)info.get("orgid");
            String dirpath = orgid +"/"+info.get("userid")+"/"+sf.format(new Date());
            String path ="/"+dirpath + "/" + file.getFileName();
            File targetFile =new File(getRequest().getRealPath("upload")+path);
            if (targetFile.exists()){
                FileUtils.forceDelete(targetFile);
            }
            FileUtils.moveFile(file.getFile(), targetFile);
            map.put("src", "/"+"upload"+ path);
            map.put("title",file.getFileName());
            success(0,"",map);
        }catch (Exception e) {
            e.printStackTrace();
            fail();
        }
    }

    public void uploadJPGBase64Str(){
        try{
            Map info = JwtUtils.validateJWTForMap(this.getPara("token"));
            if(info == null){
                fail_token();
                return;
            }
            int orgid = (int)info.get("orgid");
            File file = new File(getRequest().getRealPath("upload")+"/"+System.currentTimeMillis()+".jpg");
            String photoBase64Str = getPara("PhotoBase64Str");
            byte[] b=Base64.getDecoder().decode(photoBase64Str);
            FileOutputStream fileOutputStream=   new FileOutputStream(file);
            fileOutputStream.write(b);
            fileOutputStream.close();

            String dirpath = orgid +"/"+ sf.format(new Date()) + "/"+System.currentTimeMillis();
            String path =getRequest().getRealPath("upload")+"/"+dirpath+"/"+ file.getName();
            FileUtils.moveFile(file,new File(path));
            Map<String, String> map = new HashMap();
            map.put("url","/"+"upload/"+dirpath+"/"+file.getName());
            map.put("filename", file.getName());
            success(map);
        }catch (Exception e) {
            fail();
        }
    }

    public void uploadSingleFile(){
        try{
            Map info = JwtUtils.validateJWTForMap(this.getPara("token"));
            if(info == null){
                fail_token();
                return;
            }
            int orgid = (int)info.get("orgid");
            UploadFile file = getFile();
            String filename = file.getFileName();
            String ext = filename.substring(filename.lastIndexOf("."));
            if(file_ext_str.indexOf(ext) == -1){
                fail(1,"文件格式不正确，支持的文件类型为："+file_ext_str);
                return;
            }
            String dirpath = orgid +"/"+ sf.format(new Date()) + "/"+System.currentTimeMillis();
            String path =getRequest().getRealPath("upload")+"/"+dirpath+"/"+ file.getOriginalFileName();
            FileUtils.moveFile(file.getFile(),new File(path));
            Map<String, String> map = new HashMap();
            map.put("url","/"+"upload/"+dirpath+"/"+file.getOriginalFileName());
            map.put("filename", file.getOriginalFileName());
            success(map);
        }catch (Exception e) {
            fail();
        }
    }

    public void uploadMultipleFile(){
        try{
            Map info = JwtUtils.validateJWTForMap(this.getPara("token"));
            if(info == null){
                fail_token();
                return;
            }
            int orgid = (int)info.get("orgid");
            List<UploadFile> fileList = getFiles();
            List<String> upfileList = new ArrayList<String>();
            for (UploadFile file : fileList) {
                String filename = file.getFileName();
                String ext = filename.substring(filename.lastIndexOf("."));
                if(file_ext_str.indexOf(ext) == -1){
                    fail(1,"文件格式不正确，支持的文件类型为："+file_ext_str);
                    return;
                }
                String path ="/" + orgid+"/"+sf.format(new Date()) + "/"+System.currentTimeMillis() + file.getFileName();
                File targetFile =new File(getRequest().getRealPath("upload")+path);
                FileUtils.moveFile(file.getFile(), targetFile);
                upfileList.add(path);
            }
            success(upfileList);
        }catch (Exception e) {
            fail(0,e.getMessage());
        }
    }

    public void downloadFile(){
        try {
            String filename =getPara("filename");
            if(filename.indexOf(".") == -1){
                fail(0,"文件名不符合规范");
                return;
            }
            String[] subfilename = filename.split("\\.");
            if((filename.indexOf("/")>-1 && filename.indexOf("template/")==-1) || filename.indexOf("../")>-1 || subfilename.length != 2 || (!"xls".equals(subfilename[1]) && !"xlsx".equals(subfilename[1]))){
                fail(0,"文件名不符合规范");
                return;
            }
            String path =getRequest().getRealPath("upload")+File.separatorChar+  filename;
            log.debug(path);
            File targetFile =new File(path);
            log.debug("is exists="+targetFile.exists());
            renderFile(targetFile);

        } catch (Exception e) {
            e.printStackTrace();
            fail(0,e.getMessage());
        }
    }

    @Clear
    public void downloadChromeSetupFile(){
        try {
            String filename =getPara("filename");
            String path =getRequest().getRealPath("upload")+"/template/ChromeSetup.exe";
            log.debug(path);
            File targetFile =new File(path);
            log.debug("is exists="+targetFile.exists());
            renderFile(targetFile);

        } catch (Exception e) {
            e.printStackTrace();
            fail(0,e.getMessage());
        }
    }
}
