package com.bcxin.auth.web.controller.datasync;

import com.bcxin.auth.common.config.BMSConfig;
import com.bcxin.auth.common.constant.Constants;
import com.bcxin.auth.system.domain.DataSyncLog;
import com.bcxin.auth.system.dto.datasync.DataSyncDto;
import com.bcxin.auth.system.dto.datasync.DataSyncResultDto;
import com.bcxin.auth.system.service.IDataSyncLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


/**
 * 数据同步记录Controller
 * 
 * @author lin
 * @date 2020-12-07
 */
@Controller
@RequestMapping("/dataSync")
public class DataSyncController {

    Logger logger = LoggerFactory.getLogger(DataSyncController.class);

    @Autowired
    private IDataSyncLogService dataSyncLogService;


    /**
     * 下载文件
     * @param path
     * @param response
     */
    @RequestMapping(value = "getResource")
    public void getResource(String path, HttpServletResponse response) throws Exception {
        InputStream is = null;
        ServletOutputStream out = null;
        //判断是否为三段式，不是三段式则有问题路径
        String[] paths =  path.split("/");
        if(paths.length!=2){
            throw new Exception("路径错误！！！");
        }else{
            //判断第二段是否为日期
            if(!isValidDate(paths[0])) {
                throw new Exception("路径错误！！！");
            }
            String fileType = paths[1];
            String[] temp =fileType.split("\\.");
            if(temp.length!=2){
                throw new Exception("路径错误！！！");
            }
            //文件类型判断
            if(!StringFilter(fileType)){
                throw new Exception("路径错误！！！");
            }
        }
        File file = new File(BMSConfig.getDataSyncProfile() + path);
        if(file != null) {
            try {
                out = response.getOutputStream();
                String fileName = new String(file.getName().getBytes("UTF-8"),"iso-8859-1");
                response.addHeader("Content-Disposition","attachment;filename=" + fileName);
                is = new FileInputStream(file);
                int read = 0;
                byte[] buffer = new byte[8192];
                while ((read = is.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }
            }catch (Exception e ){
                logger.error(e.getMessage(),e);
            }finally {
                if(is!=null){
                    is.close();
                }
                if(out!=null){
                    out.flush();
                    out.close();
                }
            }
        }
    }

    /**
     * 同步
     * @param dataSyncDto
     * @return
     */
    @RequestMapping("receive")
    @ResponseBody
    public DataSyncResultDto receive(DataSyncDto dataSyncDto){
        DataSyncResultDto result = new DataSyncResultDto();
        try {
            dataSyncLogService.receive(dataSyncDto);
            result.setRetType(Constants.RETTYPE_SUCCESS);
            result.setMsg("操作成功");
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            result.setRetType(Constants.RETTYPE_FAIL);
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /**
     * 同步回调
     * @param dataSyncLog
     * @return
     */
    @RequestMapping("callback")
    @ResponseBody
    public DataSyncResultDto callback(DataSyncLog dataSyncLog){
        DataSyncResultDto result = new DataSyncResultDto();
        try {
            dataSyncLogService.callback(dataSyncLog);
            result.setRetType(Constants.RETTYPE_SUCCESS);
            result.setMsg("操作成功");
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            result.setRetType(Constants.RETTYPE_FAIL);
            result.setMsg(e.getMessage());
        }
        return result;
    }


    /***
     * 过滤非法字符
     * @param str
     * @return
     * @throws PatternSyntaxException
     */
    public static boolean StringFilter(String str) throws PatternSyntaxException {
        boolean resulst = true;
        String regEx = "[ `~!@#$%^&*()+=|{}':;',\\[\\]<>?~！@#￥%……&*（）—+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        //不允许..
        if(str.indexOf("..")>0){
            resulst =false;
        }
        //非法字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);

        if(m.find()){
            resulst = false;
        }
        return  resulst;
    }

    /****
     * 判断字符串是否为日期格式
     * @param str
     * @return
     */
    public static boolean isValidDate(String str) {
        boolean convertSuccess=true;
        // 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (ParseException e) {
            // e.printStackTrace();
            // 如果throw java.text.ParseException或者NullPointerException，就说明格式不对
            convertSuccess=false;
        }
        return convertSuccess;

    }

}
