package com.emr.controller.emrApprove;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.dao.emrReasonAnnoModel.Emr_Reason_Anno_ModelMapper;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.emrReasonAnnoModel.Emr_Reason_Anno_Model;
import com.emr.service.emrReasonAnnoModel.AnnotationTemplateService;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.ExportExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @ProjectName:AnnotationTemplateController
 * @Description:原因和批注模板页面
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/6/27 10:25
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/6/27 10:25
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("annotationTemplate/")
public class AnnotationTemplateController {
    @Autowired
    private Emr_Reason_Anno_ModelMapper annoModelMapper;
    @Autowired
    private AnnotationTemplateService annotationTemplateService;
    @Autowired
    private Emr_Reason_Anno_ModelMapper emrReasonAnnoModelMapper;
    /**
     * @ProjectName:annotationTemplateList
     * @Description:跳转到收藏管理页面
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/25 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/25 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/annotationTemplate/annotationTemplateList")
    @OptionalLog(module = "查看",methods = "原因及批注模板页面")
    @RequestMapping("annotationTemplateList")
    public String annotationTemplateList(){
        return "approveManage/annotationTemplate/annotationTemplateList";
    }

    @RequestMapping("selectNotContentAllAnnoTypeByCreater")
    @ResponseBody
    public String selectNotContentAllAnnoTypeByCreater(HttpServletRequest request){
        try {
            List<Emr_Reason_Anno_Model> types = annotationTemplateService.selectNotContentAllAnnoTypeByCreater(request);
            return JSON.toJSONString(types);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
        return "approveManage/annotationTemplate/annotationTemplateList";
    }

    /**
     * @ProjectName:getAnnoTypeNameTree
     * @Description:组织批注模板类别树
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping(value="getAnnoTypeNameTree",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public String getAnnoTypeNameTree(HttpServletRequest request){
        try {
            List<Emr_Reason_Anno_Model> types = annotationTemplateService.selectAllAnnoTypeByCreater( null,request);
            //添加首层
            Emr_Reason_Anno_Model model = new Emr_Reason_Anno_Model();
            model.setId(0);
            model.setTypeName("类别列表");
            types.add(model);
            return JSON.toJSONString(types);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @ProjectName:addAnoType
     * @Description:保存原因和批注类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "原因及批准模板类别",fieldName = "typeName")
    @RequestMapping("addAnoType")
    @ResponseBody
    public ResultUtil addAnoType(Emr_Reason_Anno_Model reasonAnnoModel, HttpServletRequest request) throws Exception{
        if(StringUtils.isBlank(reasonAnnoModel.getTypeFlag()) && reasonAnnoModel.getParentId() == 0){
            return ResultUtil.error("类别标志不能为空!");
        }
        if(StringUtils.isBlank(reasonAnnoModel.getTypeName())){
            return ResultUtil.error("类别名称不能为空!");
        }
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserId().toString();
        if(user.getRoleId() == 0){
            creater = "-1";
        }
        Emr_Reason_Anno_Model isFlag = null;
        if(StringUtils.isNoneBlank(reasonAnnoModel.getTypeFlag())){
            //验证类别名称是否重复
            isFlag = annoModelMapper.checkAnoTypeNameByCreaterAndTypeName(creater, reasonAnnoModel.getTypeFlag(),null,null);
        }
        Emr_Reason_Anno_Model annoModel = annoModelMapper.checkAnoTypeNameByCreaterAndTypeName(creater, null,reasonAnnoModel.getTypeName(),reasonAnnoModel.getParentId());
        //判断id是否有值，为null添加，否则更新
        if(null == reasonAnnoModel.getId()){
            if(isFlag == null){
                if(annoModel == null){
                    if("reason".equals(reasonAnnoModel.getTypeFlag()) || "anno".equals(reasonAnnoModel.getTypeFlag())){
                        return ResultUtil.error("类别标志不能重复!");
                    }
                    annotationTemplateService.addAnno(reasonAnnoModel,request);
                }else{
                    return ResultUtil.error("类别名称不能重复!");
                }
            }else{
                return ResultUtil.error("类别标志不能重复!");
            }
        }else{
            if(null != isFlag && !isFlag.getId().equals(reasonAnnoModel.getId())){
                return ResultUtil.error("类别标志不能重复!");
            }else{
                if(null != annoModel && !annoModel.getId().equals(reasonAnnoModel.getId())){
                    return ResultUtil.error("类别名称不能重复!");
                }else{
                    Emr_Reason_Anno_Model reason = annoModelMapper.checkAnoTypeNameByCreaterAndTypeName(null, "reason",null,null);
                    Emr_Reason_Anno_Model anno = annoModelMapper.checkAnoTypeNameByCreaterAndTypeName(null, "anno",null,null);
                    if("reason".equals(reasonAnnoModel.getTypeFlag()) || "anno".equals(reasonAnnoModel.getTypeFlag())){
                        if(null != reason && !reason.getId().equals(reasonAnnoModel.getId())){
                            return ResultUtil.error("类别标志不能重复!");
                        }
                        if(null != anno && !anno.getId().equals(reasonAnnoModel.getId())){
                            return ResultUtil.error("类别标志不能重复!");
                        }
                    }
                    annotationTemplateService.updateAnno(reasonAnnoModel,request);
                }
            }
        }
        ResultUtil result = new ResultUtil();
        result.setCode(0);
        result.setMsg(reasonAnnoModel.getId().toString());
        return result;
    }

    /**
     * @ProjectName:addAnno
     * @Description:保存原因和批注模板
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "原因及批注模板",fieldName = "content")
    @RequestMapping("addAnno")
    @ResponseBody
    public ResultUtil addAnno(Emr_Reason_Anno_Model reasonAnnoModel,HttpServletRequest request) throws Exception{
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserName();
        //根据类别验证内容是否是否存在
        Emr_Reason_Anno_Model model = annoModelMapper.checkContentByParentId(creater, reasonAnnoModel);
        //判断id是否有值，为null添加，否则更新
        if(null == reasonAnnoModel.getId()){
            if(model == null){
                annotationTemplateService.addAnno(reasonAnnoModel,request);
            }else{
                return ResultUtil.error("相同模板类别该内容已存在!");
            }
        }else{
            if(null != model && !model.getId().equals(reasonAnnoModel.getId())){
                return ResultUtil.error("相同模板类别该内容已存在!");
            }else{
                annotationTemplateService.updateAnno(reasonAnnoModel,request);
            }
        }
        return ResultUtil.ok();
    }

    /**
     * @ProjectName:deleteAnoType
     * @Description:删除类别
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019/6/26 15:37
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019/6/26 15:37
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "删除",methods = "原因及批注模板")
    @RequestMapping("deleteAnoType")
    @ResponseBody
    public ResultUtil deleteAnoType(Integer id) throws Exception{
        annotationTemplateService.deleteByPrimaryKey(id);
        return ResultUtil.ok();
    }

    /**
     * @MethodName: getAnnoTemplateById
     * @Description: 通过id查询对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getAnnoTemplateById")
    @ResponseBody
    public String getAnnoTemplateById(Integer id){
        try {
            Emr_Reason_Anno_Model model = annoModelMapper.getAnnoTemplateById(id);
            return JSON.toJSONString(model);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getAnnoTemplateList
     * @Description: 获取批注模板列表
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getAnnoTemplateList")
    @ResponseBody
    public String getAnnoTemplateList(Integer page, Integer limit,Emr_Reason_Anno_Model reasonAnnoModel,HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        List<Emr_Reason_Anno_Model> models = null;
        try{
            //根据用户和查询批注模板列表
            models = annotationTemplateService.selectAnnoTemplateListByCreater("IS NULL",reasonAnnoModel,request);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
        //匹配权限
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        Set<String> menus = user.getMenus();
        if(null != models && !models.isEmpty()){
            if(null != menus && !menus.isEmpty()){
                int updateOper = 0;
                int deleteOper = 0;
                for(String menu : menus){
                    if(StringUtils.isNotBlank(menu)){
                        if("/annotationTemplate/updateAnno".equals(menu)){
                            updateOper = 1;
                        }
                        if("/annotationTemplate/deleteAno".equals(menu)){
                            deleteOper = 1;
                        }
                    }
                }
                for (Emr_Reason_Anno_Model obj : models){
                    obj.setUpdateOper(updateOper);
                    obj.setDeleteOper(deleteOper);
                }
            }
        }
        PageInfo pageInfo = new PageInfo<>(models);
        return JSON.toJSONString(pageInfo);
    }

    /**
     * @MethodName: exportExcel
     * @Description: 根据搜索条件导出excel
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-27
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-27
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/annotationTemplate/exportExcel")
    @OptionalLog(module = "导出excel",methods = "原因及批注模板")
    @RequestMapping(value="exportExcel",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcel(HttpServletResponse response,Emr_Reason_Anno_Model reasonAnnoModel,HttpServletRequest request,String checks){
        String tableThNames = "类别,内容,是否有效,创建人,创建时间,修改人,修改时间";
        String fieldCns = "typeName,content,effectiveCn,creater,createTime,updater,updateTime";
        //构造excel的数据
        try {
            List<Emr_Reason_Anno_Model> models = new ArrayList<>();
            if(StringUtils.isNotBlank(checks)){
                models = emrReasonAnnoModelMapper.selectAllByIds(checks);
            }else{
                models = annotationTemplateService.selectAnnoTemplateListByCreater("IS NULL",reasonAnnoModel,request);
            }
            if(null != models && !models.isEmpty()){
                for (Emr_Reason_Anno_Model model : models) {
                    if (model.getEffective() == 1) {
                        model.setEffectiveCn("是");
                    } else {
                        model.setEffectiveCn("否");
                    }
                }
            }
            //文件名
            String fileName = "原因和标注模板导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,models,fileName,response);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    /**
     * @MethodName: getAnnoTemplateByParentId
     * @Description: 通过parentId查询对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-06-28
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-28
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getAnnoTemplateByParentId")
    @ResponseBody
    public String getAnnoTemplateByParentId(Integer parentId){
        try {
            String content = annoModelMapper.selectContentByParentId(parentId);
            return JSON.toJSONString(content);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }
}
