package com.emr.controller.otherManage;

import com.alibaba.fastjson.JSON;
import com.emr.entity.EmrComomSet;
import com.emr.entity.ResultUtil;
import com.emr.service.CommomSetService;
import com.emr.util.ExceptionPrintUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;

@Controller
@RequestMapping("commomSet/")
public class CommomSetController {
    @Autowired
    private CommomSetService commomSetService;

    @RequestMapping("commomSetList")
    public String commomSetList(Model model){
        try{
            EmrComomSet comomSet = commomSetService.selectByPrimaryKey(1);
            model.addAttribute("comomSet",comomSet);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "otherManage/commomSetList";
    }

    @RequestMapping("updateCommomSet")
    @ResponseBody
    public ResultUtil updateCommomSet(EmrComomSet comomSet) throws Exception{
        //判断图片根目录的合法性
        String newPicRoot = comomSet.getNewPicRoot();
        newPicRoot = newPicRoot.trim();
        //验证目录是否正确
        String fileRegex = "^[A-z]:\\\\([^|><?*\":\\/]*\\\\)*([^|><?*\":\\/]*)?$";
        boolean matches = newPicRoot.matches(fileRegex);
        if(!matches){
            return ResultUtil.error("目录路径格式不正确!");
        }
        //验证是否有特殊字符
        String[] split = newPicRoot.split("\\\\");
        for(int i = 0;i < split.length;i++){
            if(i != 0){
                boolean flag = split[i].matches("[^\\s\\\\/:\\*\\?\\\"<>\\|](\\x20|[^\\s\\\\/:\\*\\?\\\"<>\\|])*[^\\s\\\\/:\\*\\?\\\"<>\\|\\.]$");
                if(!flag){
                    return ResultUtil.error("不能存在特殊符号/ \\ \": | * ? < >");
                }
            }
        }
        //验证盘符是否存在d:/
        String str = newPicRoot.substring(0,1) + ":/";
        if(!new File(str).exists()){
            return ResultUtil.error(newPicRoot.substring(0,1) + "盘符不存在!");
        }
        comomSet.setNewPicRoot(newPicRoot);
        commomSetService.update(comomSet);
        return ResultUtil.ok();
    }

    @RequestMapping(value = "getCommomSetList")
    @ResponseBody
    public String getCommomSetList(){
        EmrComomSet comomSet = null;
        try {
            comomSet = commomSetService.selectByPrimaryKey(1);
        } catch (Exception e) {
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return JSON.toJSONString(comomSet);
    }
}
