package com.emr.controller.emrApprove;

import com.alibaba.fastjson.JSON;
import com.emr.annotation.OptionalLog;
import com.emr.controller.FormTokenFlagUtil;
import com.emr.dao.CommomMapper;
import com.emr.dao.Emr_DictionaryMapper;
import com.emr.dao.approve.Emr_Apply_ApproveMapper;
import com.emr.entity.Emr_Dictionary;
import com.emr.entity.Power_User;
import com.emr.entity.ResultUtil;
import com.emr.entity.approve.Emr_Apply_Approve;
import com.emr.entity.emrReasonAnnoModel.Emr_Reason_Anno_Model;
import com.emr.service.CommomService;
import com.emr.service.ImportExcel.ImportExcelEntity;
import com.emr.service.ImportExcel.ImportExcelUtil;
import com.emr.service.approve.ApplyApproveService;
import com.emr.service.emrReasonAnnoModel.AnnotationTemplateService;
import com.emr.util.ConvertToSelectJson;
import com.emr.util.DateUtils;
import com.emr.util.ExceptionPrintUtil;
import com.emr.util.ExportExcelUtil;
import com.emr.vo.User;
import com.emr.vo.commomSearch.CommomVo;
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.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ProjectName:ApproveController
 * @Description:借阅审批管理
 * @Param 传输参数
 * @Return
 * @Author: 曾文和
 * @CreateDate: 2019/5/31 11:16
 * @UpdateUser: 曾文和
 * @UpdateDate: 2019/5/31 11:16
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Controller
@RequestMapping("approve/")
public class ApproveController {
    @Autowired
    private ApplyApproveService applyApproveService;
    @Autowired
    private CommomMapper commomMapper;
    @Autowired
    private Emr_DictionaryMapper dictionaryMapper;
    @Autowired
    private AnnotationTemplateService annotationTemplateService;
    @Autowired
    private Emr_Apply_ApproveMapper applyApproveMapper;
    @Value("${POWER_URLHEAD}")
    private String POWER_URLHEAD;
    @Value("${applyApproveFlag}")
    private String applyApproveFlag;
    @Autowired
    private CommomService commomService;
    /**
     * @MethodName: approveListByAppleStatus
     * @Description: 查询该用户该记录是否有未提交，有则返回
     * @Param  String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-31
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-05-31
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("approveListByAppleStatus")
    @ResponseBody
    public String approveListByAppleStatus(String patientId,short type, HttpServletRequest request){
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        try {
            List<Emr_Apply_Approve> approves = applyApproveService.selectNotSumbitPatientIdsByUser(userName, patientId,type);
            if(null != approves && !approves.isEmpty()){
                return JSON.toJSONString(approves.get(approves.size() - 1));
            }else{
                return null;
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: addApplyApprove
     * @Description: 查询页面借阅申请
     * @Param  String patientId:patientId
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-05-30
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 提取添加申请人和申请时间到添加申请接口
     * @Version: 1.0
     */
    @RequiresPermissions(value={"/commom/addApplyApprove"})
    @OptionalLog(module = "保存",methods = "查询页面保存借阅申请")
    @RequestMapping("addApplyApprove")
    @ResponseBody
    public ResultUtil addApplyApprove(Emr_Apply_Approve applyApprove, String patientIds,HttpServletRequest request) throws Exception{
        boolean flag = FormTokenFlagUtil.isFlag(request);
        if (!flag) {
            return ResultUtil.error("请不要重复提交!");
        }
        List<CommomVo> commomtables = commomMapper.selectAllByPatients(patientIds);
        if(null != commomtables && !commomtables.isEmpty()) {
            Power_User powerUser = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //查询是否未过期
            List<Emr_Apply_Approve> approves = applyApproveMapper.selectPatientIdsByUserAndApplyStatus(powerUser.getUserName(), patientIds, applyApprove.getApplyType());
            if (null != approves && !approves.isEmpty()) {
                if (commomtables.size() == 1) {
                    return ResultUtil.error("该病案另一个申请还处于有效期，无须重复申请!");
                }
                for (int i = 0; i < commomtables.size(); i++) {
                    //剩下的批量添加
                    for (Emr_Apply_Approve approve : approves) {
                        if (approve.getPatientId().equals(commomtables.get(i).getPatientId())) {
                            //移除
                            commomtables.remove(i);
                        }
                    }
                }
            }
            if (!commomtables.isEmpty()) {
                if (applyApproveFlag.equals("1")){
                    SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd");
                    List<String> expireTimeList = applyApproveService.expireTime(fmt1.format(new Date()),applyApprove.getEffeDays());
                    String s = expireTimeList.get(expireTimeList.size()-1);
                    applyApprove.setEffeTime(s);
                }
                applyApprove.setApplyer(powerUser.getUserName());
                applyApprove.setApplyTime(fmt.format(new Date()));
                List<Emr_Apply_Approve> list = new ArrayList<>();
                ///查询表列数
                int colCount = commomMapper.selectColByTableName("emr_apply_approve");
                int simpleInsertCount = 2100/colCount;
                for (int i = 0; i < commomtables.size(); i++) {
                    //处理批量添加sql太长问题，设定个数为180
                    if(i > 0 && list.size()%simpleInsertCount == 0){
                        list.clear();
                    }
                    Emr_Apply_Approve applyApproveInsert = new Emr_Apply_Approve();
                    BeanUtils.copyProperties(applyApprove, applyApproveInsert);
                    BeanUtils.copyProperties(commomtables.get(i), applyApproveInsert);
                    if(StringUtils.isNotBlank(commomtables.get(i).getDisDate())){
                        applyApproveInsert.setDisDate(DateUtils.strToDateLong(commomtables.get(i).getDisDate()));
                    }
                    list.add(applyApproveInsert);
                    if(list.size() == 1 && list.get(0).getId() != null){
                        applyApproveService.updateEmrApplyApprove(list.get(0));
                    }else{
                        //是180的倍数或最后一个
                        if((list.size()%simpleInsertCount == 0 || i == commomtables.size() - 1)){
                            applyApproveService.SimpleInsert(list);
                        }
                    }
                }
                //推送给权限系统下发审批人通知
                String applyStateTemp = "2";
                if(applyApprove.getApplyState().equals(applyStateTemp)){
                    sendPowerApproveInterface(applyApprove.getApplyType(),commomtables.size());
                }
            } else {
                return ResultUtil.error("该病案另一个申请还处于有效期，无须重复申请!");
            }
            return ResultUtil.ok();
        }else{
            return ResultUtil.error("请至少选中一个!");
        }
    }

    //推送给权限系统下发审批人通知
    private void sendPowerApproveInterface(String applyType,Integer count) throws Exception{
        //查询申请类型
        List<Emr_Dictionary> dictionaryList = dictionaryMapper.selectDictionaryByTypeCode("apply_type");
        String applyTypeName = "";
        if(null != dictionaryList && !dictionaryList.isEmpty()){
            for(Emr_Dictionary dictionary : dictionaryList){
                if(dictionary.getCode().equals(applyType)){
                    applyTypeName = dictionary.getName();
                    break;
                }
            }
        }
        //发送通知
        applyApproveService.sendNotice(applyTypeName,count);
    }

    /**
     * @MethodName: approveManageList
     * @Description: 跳转到申请列表
     * @Param
     * @Author: 曾文和
     * @CreateDate: 2019-06-30
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-06-30
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    //174
    @RequiresPermissions("/approve/approveList174")
    @OptionalLog(module = "查看",methods = "申请列表页面")
    @RequestMapping("approveList174")
    public String approveList174(){
        return "approveManage/approveList/approveList174";
    }

    @RequiresPermissions("/approve/approveList")
    @OptionalLog(module = "查看",methods = "申请列表页面")
    @RequestMapping("approveList")
    public String approveList(){
        return "approveManage/approveList/approveList174";
    }

    /**
     * @MethodName: loadType
     * @Description: 异步加载申请类型
     * @Param
     * @Author: 曾文和
     * @CreateDate: 2019-12-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-12-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("loadType")
    @ResponseBody
    public String loadType(){
        try {
            List<Emr_Dictionary> applyTypes = dictionaryMapper.selectDictionaryByTypeCode("apply_type");
            return ConvertToSelectJson.toSelectJson(applyTypes,"code","name");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: loadReasonModle
     * @Description: 异步加载申请原因模板
     * @Param
     * @Author: 曾文和
     * @CreateDate: 2019-12-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-12-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("loadReasonModle")
    @ResponseBody
    public String loadReasonModle(HttpServletRequest request){
        try {
            List<Emr_Reason_Anno_Model> models = annotationTemplateService.selectReasonOrAnnoTemplateList("reason",request);
            return ConvertToSelectJson.toSelectJson(models,"id","typeName");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: addApply
     * @Description: 收藏页面与添加申请页面添加申请
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @OptionalLog(module = "保存",methods = "收藏页面与添加申请页面借阅申请",fieldName = "inpatientNo",tableName = "emr_apply_approve")
    @RequestMapping("addApply")
    @ResponseBody
    public ResultUtil addApply(Emr_Apply_Approve applyApprove,String startTime2,String endTime2,HttpServletRequest request) throws Exception{
        Power_User powerUser = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        if(StringUtils.isBlank(applyApprove.getPatientId())){
            if(null != applyApprove.getAdmissTimes() && StringUtils.isNotBlank(applyApprove.getInpatientNo())&&StringUtils.isNotBlank(applyApprove.getName())){
                //如果patientId不存在，通过病案号，姓名，住院次数查询patientId
                List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(applyApprove.getAdmissTimes(), applyApprove.getInpatientNo(), applyApprove.getName(),startTime2,endTime2);
                if(null != patientIdList && !patientIdList.isEmpty()){
                    if(patientIdList.size() == 1){
                        applyApprove.setPatientId(patientIdList.get(0));
                    }else{
                        return ResultUtil.error("查询结果不唯一,符合条件共计"+patientIdList.size()+"条");
                    }
                }else{
                    return ResultUtil.error("查询无该病案!");
                }
            }else{
                return ResultUtil.error("查询无该病案!");
            }
        }
        //查询通过审批且未过期的patientId集合
        //通过patientId查询病案对象获取和出院时间
        List<CommomVo> commomVos = commomMapper.selectAllByPatients("'"+applyApprove.getPatientId()+"'");
        BeanUtils.copyProperties(commomVos.get(0),applyApprove);
        String patientId = "'" + applyApprove.getPatientId() + "'";
        List<Emr_Apply_Approve> approves = applyApproveMapper.selectPatientIdsByUserAndApplyStatus(powerUser.getUserName(),patientId,applyApprove.getApplyType());
        if(null != approves && !approves.isEmpty()){
            return ResultUtil.error("该病案另一个申请还处于有效期，无须重复申请!");
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        applyApprove.setDisDate(fmt.parse(commomVos.get(0).getDisDate()));
        Integer id = applyApprove.getId();
        //存在则更新，不存在新增
        if(id != null){
            //若是确认提交,将审核信息置空
            if("2".equals(applyApprove.getApplyState())){
                applyApprove.setApprover("");
                applyApprove.setApproveTime("");
                applyApprove.setApproveState("");
                applyApprove.setApproveNotes("");
            }
            applyApproveService.updateEmrApplyApprove(applyApprove);
        }else{
            boolean flag = FormTokenFlagUtil.isFlag(request);
            if (flag) {
                applyApproveService.addEmrApplyApprove(applyApprove,request);
            }else{
                return ResultUtil.error("请不要重复提交!");
            }
        }
        //是确认提交情况下发送通知
        String applyStateTemp = "2";
        if(applyApprove.getApplyState().equals(applyStateTemp)){
            sendPowerApproveInterface(applyApprove.getApplyType(),1);
        }
        return ResultUtil.ok();
    }

    //脐血库
    @OptionalLog(module = "保存",methods = "收藏页面与添加申请页面借阅申请",fieldName = "inpatientNo",tableName = "emr_apply_approve")
    @RequestMapping("addApplyBlood")
    @ResponseBody
    public ResultUtil addApplyBlood(Emr_Apply_Approve applyApprove,String startTime2,String endTime2,HttpServletRequest request) throws Exception{
        Power_User powerUser = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        if(StringUtils.isBlank(applyApprove.getPatientId())){
            if(StringUtils.isNotBlank(applyApprove.getInpatientNo())&&StringUtils.isNotBlank(applyApprove.getName())){
                //如果patientId不存在，通过病案号，姓名，住院次数查询patientId
                List<String> patientIdList = commomMapper.selectPatientIdByAdmissTimesAndInpatientNoAndName(applyApprove.getAdmissTimes(), applyApprove.getInpatientNo(), applyApprove.getName(),startTime2,endTime2);
                if(null != patientIdList && !patientIdList.isEmpty()){
                    if(patientIdList.size() == 1){
                        applyApprove.setPatientId(patientIdList.get(0));
                    }else{
                        return ResultUtil.error("查询结果不唯一,符合条件共计"+patientIdList.size()+"条");
                    }
                }else{
                    return ResultUtil.error("查询无该档案!");
                }
            }else{
                return ResultUtil.error("查询无该档案!");
            }
        }
        //查询通过审批且未过期的patientId集合
        //通过patientId查询病案对象获取和出院时间
        List<CommomVo> commomVos = commomMapper.selectAllByPatients("'"+applyApprove.getPatientId()+"'");
        BeanUtils.copyProperties(commomVos.get(0),applyApprove);
        String patientId = "'" + applyApprove.getPatientId() + "'";
        List<Emr_Apply_Approve> approves = applyApproveMapper.selectPatientIdsByUserAndApplyStatus(powerUser.getUserName(),patientId,applyApprove.getApplyType());
        if(null != approves && !approves.isEmpty()){
            return ResultUtil.error("该档案另一个申请还处于有效期，无须重复申请!");
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //applyApprove.setDisDate(fmt.parse(commomVos.get(0).getDisDate()));
        Integer id = applyApprove.getId();
        //存在则更新，不存在新增
        if(id != null){
            //若是确认提交,将审核信息置空
            if("2".equals(applyApprove.getApplyState())){
                applyApprove.setApprover("");
                applyApprove.setApproveTime("");
                applyApprove.setApproveState("");
                applyApprove.setApproveNotes("");
            }
            applyApproveService.updateEmrApplyApprove(applyApprove);
        }else{
            boolean flag = FormTokenFlagUtil.isFlag(request);
            if (flag) {
                applyApproveService.addEmrApplyApprove(applyApprove,request);
            }else{
                return ResultUtil.error("请不要重复提交!");
            }

        }
        return ResultUtil.ok();
    }

    /**
     * @MethodName: getApproveList
     * @Description: 获取申请列表分页数据
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getApproveList")
    @ResponseBody
    public String getApproveList(Integer page, Integer limit,Emr_Apply_Approve approve, String startTime1,
                                 String endTime1,HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        try{
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            List<User> userList = commomService.getUserList(user.getUserName(), request);
            //查询条件用户名转姓名
            setSearchApplyerAndApprover(approve,userList);
            List<Emr_Apply_Approve> approves = applyApproveService.selectAllApproveByCreater(approve,
                    startTime1, endTime1,null,null,request);
            if(null != approves && !approves.isEmpty()){
                Set<String> menus = user.getMenus();
                if(null != menus && !menus.isEmpty()){
                    int addOper = 0;
                    int updateOper = 0;
                    int deleteOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/approve/addApplyApprove".equals(menu)){
                                addOper = 1;
                            }
                            if("/approve/updateApplyApprove".equals(menu)){
                                updateOper = 1;
                            }
                            if("/approve/deleteApproveById".equals(menu)){
                                deleteOper = 1;
                            }
                        }
                    }
                    for (Emr_Apply_Approve obj : approves){
                        obj.setAddOper(addOper);
                        obj.setUpdateOper(updateOper);
                        obj.setDeleteOper(deleteOper);
                        //转换用户名
                        //获取申请者工号
                        String applyer = obj.getApplyer();
                        if(!CollectionUtils.isEmpty(userList)){
                            for(User user1 : userList){
                                String name = user1.getName();
                                if(StringUtils.isNotBlank(applyer) && user1.getUserName().equals(applyer)){
                                    obj.setApplyer(name);
                                }
                            }
                        }
                    }
                }
            }
            PageInfo pageInfo = new PageInfo<>(approves);
            return JSON.toJSONString(pageInfo);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getApproveById
     * @Description: 通过id查询包括患者姓名的申请对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getApproveById")
    @ResponseBody
    public String getApproveById(Integer id,HttpServletRequest request){
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String creater = user.getUserName();
        try{
            List<Emr_Apply_Approve> approve = applyApproveMapper.selectApproveById(creater,id);
            Emr_Apply_Approve emrApplyApprove = approve.get(0);
            if(null != emrApplyApprove){
                Date disDate = emrApplyApprove.getDisDate();
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                if(null != disDate){
                    emrApplyApprove.setDisTime(fmt.format(disDate));
                }
            }
            List<User> userList = commomService.getUserList(user.getUserName(), request);
            //查询条件用户名转姓名
            for (Emr_Apply_Approve obj : approve){
                //转换用户名
                //获取申请者工号
                String applyer = obj.getApplyer();
                if(!CollectionUtils.isEmpty(userList)){
                    for(User user1 : userList){
                        String name = user1.getName();
                        if(StringUtils.isNotBlank(applyer) && user1.getUserName().equals(applyer)){
                            obj.setApplyer(name);
                        }
                    }
                }
            }
            return JSON.toJSONString(emrApplyApprove);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: deleteApproveById
     * @Description: 删除申请对象
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/approve/deleteApproveById")
    @OptionalLog(module = "删除",methods = "删除借阅申请",fieldName = "inpatientNo",tableName = "emr_apply_approve")
    @RequestMapping("deleteApproveById/{id}")
    @ResponseBody
    public ResultUtil deleteApproveById(@PathVariable("id") Integer id) throws Exception{
        applyApproveService.deleteByPrimaryKey(id);
        return ResultUtil.ok();
    }


    /**
     * @MethodName: exportExcelApplyList
     * @Description: 根据搜索条件导出excel,申请列表集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/approve/exportExcelApplyList")
    @OptionalLog(module = "导出excel",methods = "申请列表")
    @RequestMapping(value="exportExcelApplyList",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcelApplyList(HttpServletResponse response, Emr_Apply_Approve approve,
                                     String startTime, String endTime,HttpServletRequest request,String checks){
        String tableThNames = "申请人,申请日期,有效日期,有效天数,姓名,病案号,住院次数,出院日期,申请原因,申请类型,申请状态,审批状态,批注内容";
        String fieldCns = "applyer,applyTime,effeTime,effeDays,name,inpatientNo,admissTimes,disTime,applyReason,applyType,applyState,approveState,approveNotes";
        try {
            List<Emr_Apply_Approve> approves = new ArrayList<>();
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            List<User> userList = commomService.getUserList(user.getUserName(), request);
            //构造excel的数据
            if(StringUtils.isNotBlank(checks)){
                approves = applyApproveMapper.selectAllByIds(checks);
            }else{
                //查询条件用户名转姓名
                setSearchApplyerAndApprover(approve,userList);
                approves = applyApproveService.selectAllApproveByCreater(approve, startTime, endTime,null,null,request);
            }
            if(null != approves && !approves.isEmpty()){
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
                for (Emr_Apply_Approve obj : approves) {
                    if(null != obj.getDisDate()){
                        obj.setDisTime(fmt.format(obj.getDisDate()));
                        //转换用户名
                        //获取申请者工号
                        String applyer = obj.getApplyer();
                        if(!CollectionUtils.isEmpty(userList)){
                            for(User user1 : userList){
                                String name = user1.getName();
                                if(StringUtils.isNotBlank(applyer) && user1.getUserName().equals(applyer)){
                                    obj.setApplyer(name);
                                }
                            }
                        }
                    }
                }
            }
            //文件名
            String fileName = "申请借阅导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,approves,fileName,response);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    /**
     * @MethodName: approveManageList
     * @Description: 跳转到借阅审批管理页面
     * @Param
     * @Author: 曾文和
     * @CreateDate: 2019-07-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    //174
    @RequiresPermissions("/approve/approveManageList174")
    @OptionalLog(module = "查看",methods = "借阅审批管理页面")
    @RequestMapping("approveManageList174")
    public String approveManageList174(Integer flag,Model model){
        model.addAttribute("flag",flag);
        return "approveManage/approveManageList/approveManageList174";
    }

    @RequiresPermissions("/approve/approveManageList")
    @OptionalLog(module = "查看",methods = "借阅审批管理页面")
    @RequestMapping("approveManageList")
    public String approveManageList(Integer flag,Model model){
        model.addAttribute("flag",flag);
        return "approveManage/approveManageList/approveManageList174";
    }
    /**
     * @MethodName: loadAnnoModle
     * @Description: 异步加载批注类别模板
     * @Param
     * @Author: 曾文和
     * @CreateDate: 2019-12-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-12-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("loadAnnoModle")
    @ResponseBody
    public String loadAnnoModle(HttpServletRequest request){
        try {
            List<Emr_Reason_Anno_Model> models = annotationTemplateService.selectReasonOrAnnoTemplateList("anno",request);
            return ConvertToSelectJson.toSelectJson(models,"id","typeName");
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询条件用户名转姓名
     * @param approve
     * @param userList
     */
    private void setSearchApplyerAndApprover(Emr_Apply_Approve approve,List<User> userList){
        String applyer1 = approve.getApplyer();
        String approver1 = approve.getApprover();
        String str = "\'abcxyz\'";
        if(StringUtils.isNotBlank(applyer1)){
            StringBuilder applyerBuild = new StringBuilder();
            if(!CollectionUtils.isEmpty(userList)){
                for(User userTemp : userList){
                    if(StringUtils.isNotBlank(userTemp.getName())) {
                        if (userTemp.getName().contains(applyer1)) {
                            if (StringUtils.isNotBlank(applyerBuild)) {
                                applyerBuild.append(",");
                            }
                            applyerBuild.append("'").append(userTemp.getUserName()).append("'");
                        }
                    }
                }
                if(StringUtils.isNotBlank(applyerBuild)) {
                    approve.setApplyer(applyerBuild.toString());
                }else{
                    approve.setApplyer(str);
                }
            }else{
                approve.setApplyer("");
            }
        }
        if(StringUtils.isNotBlank(approver1)){
            StringBuilder applyerBuild = new StringBuilder();
            if(!CollectionUtils.isEmpty(userList)){
                for(User userTemp : userList){
                    if(StringUtils.isNotBlank(userTemp.getName())) {
                        if (userTemp.getName().contains(approver1)) {
                            if (StringUtils.isNotBlank(applyerBuild)) {
                                applyerBuild.append(",");
                            }
                            applyerBuild.append("'").append(userTemp.getUserName()).append("'");
                        }
                    }
                }
                if(StringUtils.isNotBlank(applyerBuild)) {
                    approve.setApprover(applyerBuild.toString());
                }else{
                    approve.setApprover(str);
                }
            }else{
                approve.setApprover("");
            }
        }
    }

    /**
     * @MethodName: getApproveManageList
     * @Description: 获取审批列表分页数据
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getApproveManageList")
    @ResponseBody
    public String getApproveManageList(Integer page, Integer limit,Emr_Apply_Approve approve,
                                       String startTime1, String endTime1,String startTime2, String endTime2,HttpServletRequest request){
        if(null != page && null != limit){
            PageHelper.startPage(page, limit);
        }
        approve.setApplyState("已提交");
        try{
            //匹配权限
            Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
            List<User> userList = commomService.getUserList(user.getUserName(), request);
            //查询条件用户名转姓名
            setSearchApplyerAndApprover(approve,userList);
            List<Emr_Apply_Approve> approves = applyApproveService.selectAllApprove(approve, startTime1, endTime1,startTime2,endTime2,request);
            if(null != approves && !approves.isEmpty()){
                Set<String> menus = user.getMenus();
                if(null != menus && !menus.isEmpty()){
                    int updateOper = 0;
                    for(String menu : menus){
                        if(StringUtils.isNotBlank(menu)){
                            if("/approve/updateApprove".equals(menu)){
                                updateOper = 1;
                            }
                        }
                    }
                    for (Emr_Apply_Approve obj : approves){
                        obj.setUpdateOper(updateOper);
                        //转换用户名
                        //获取申请者工号
                        String applyer = obj.getApplyer();
                        //获取审批者工号
                        String approver = obj.getApprover();
                        if(!CollectionUtils.isEmpty(userList)){
                            for(User user1 : userList){
                                String name = user1.getName();
                                if(StringUtils.isNotBlank(applyer) && user1.getUserName().equals(applyer)){
                                    obj.setApplyer(name);
                                    obj.setDeptName(user1.getDeptName());
                                }
                                if(StringUtils.isNotBlank(approver) && user1.getUserName().equals(approver)){
                                    obj.setApprover(name);
                                }
                            }
                        }
                    }
                }
            }
            PageInfo pageInfo = new PageInfo<>(approves);
            return JSON.toJSONString(pageInfo);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: updateApprove
     * @Description: 借阅批注
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/approve/updateApprove")
    @OptionalLog(module = "保存",methods = "批注借阅审批申请")
    @RequestMapping(value = "updateApprove")
    @ResponseBody
    public ResultUtil updateApprove(Emr_Apply_Approve applyApprove,HttpServletRequest request) throws Exception{
        //如果等一就是开启了过滤节假日
        if (applyApproveFlag.equals("1")){
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            String userName = user.getUserName();
            applyApprove.setApprover(userName);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            List<String> expireTimeList = applyApproveService.expireTime(fmt.format(new Date()),applyApprove.getEffeDays());
            String s = expireTimeList.get(expireTimeList.size()-1);
            applyApprove.setApproveTime(fmt.format(new Date()));
            applyApprove.setEffeTime(s);
            applyApproveService.updateEmrApplyApprove(applyApprove);
        }else {
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            String userName = user.getUserName();
            applyApprove.setApprover(userName);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            applyApprove.setApproveTime(fmt.format(new Date()));
            applyApproveService.updateEmrApplyApprove(applyApprove);
        }
        return ResultUtil.ok();
    }

    @RequiresPermissions("/approve/updateApprove")
    @OptionalLog(module = "保存",methods = "批注借阅审批申请")
    @RequestMapping("updateApproves")
    @ResponseBody
    public ResultUtil updateApprovs(String[] ids, String state, String note, HttpServletRequest request) throws Exception{
        Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
        String userName = user.getUserName();
        if (null != ids || ids.length > 0){
            StringBuilder idsStr = new StringBuilder();
            for (int i = 0; i < ids.length; i++) {
                if(i != ids.length - 1) {
                    idsStr.append(ids[i] + ",");
                }else {
                    idsStr.append(ids[i]);
                }
            }
            Emr_Apply_Approve applyApprove = new Emr_Apply_Approve();
            applyApprove.setApprover(userName);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            applyApprove.setApproveTime(sdf.format(new Date()));
            applyApprove.setApproveState(state);
            applyApprove.setApproveNotes(note);
            //驳回时提交状态置为保存未提交
            if("2".equals(state)){
                applyApprove.setApplyState("1");
            }
            applyApproveService.SimpleUpdate(applyApprove,idsStr.toString());
        }
        return ResultUtil.ok();
    }




    /**
     * @MethodName: exportExcelApproveList
     * @Description: 根据搜索条件导出excel,审批列表集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-01
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-01
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequiresPermissions("/approve/exportExcelApproveList")
    @OptionalLog(module = "导出excel",methods = "借阅批准管理")
    @RequestMapping(value="exportExcelApproveList",produces = {"text/json;charset=UTF-8"})
    @ResponseBody
    public void exportExcelApproveList(HttpServletResponse response, Emr_Apply_Approve approve,
                                       String startTime1, String endTime1,String startTime2, String endTime2,HttpServletRequest request,String checks) throws Exception{
        String tableThNames = "申请人,申请科室,申请日期,有效日期,有效天数,姓名,病案号,住院次数,出院日期,申请原因,申请类型,审批状态,审批时间,审批人,批注内容";
        String fieldCns = "applyer,deptName,applyTime,effeTime,effeDays,name,inpatientNo,admissTimes,disTime,applyReason,applyType,approveState,approveTime,approver,approveNotes";
        List<Emr_Apply_Approve> approves = new ArrayList<>();
        //匹配权限
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        List<User> userList = commomService.getUserList(user.getUserName(), request);
        try {
            //构造excel的数据
            if(StringUtils.isNotBlank(checks)){
                approves = applyApproveMapper.selectAllByIds(checks);
            }else{
                approve.setApplyState("已提交");
                //查询条件用户名转姓名
                setSearchApplyerAndApprover(approve,userList);
                approves = applyApproveService.selectAllApprove(approve, startTime1, endTime1,
                        startTime2,endTime2,request);
            }
            if(null != approves && !approves.isEmpty()){
                SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (Emr_Apply_Approve obj : approves) {
                    if(null != obj.getDisDate()){
                        obj.setDisTime(fmt.format(obj.getDisDate()));
                        //转换用户名
                        //获取申请者工号
                        String applyer = obj.getApplyer();
                        //获取审批者工号
                        String approver = obj.getApprover();
                        if(!CollectionUtils.isEmpty(userList)){
                            for(User user1 : userList){
                                String name = user1.getName();
                                if(StringUtils.isNotBlank(applyer) && user1.getUserName().equals(applyer)){
                                    obj.setApplyer(name);
                                    obj.setDeptName(user1.getDeptName());
                                }
                                if(StringUtils.isNotBlank(approver) && user1.getUserName().equals(approver)){
                                    obj.setApprover(name);
                                }
                            }
                        }
                    }
                }
            }
            //文件名
            String fileName = "借阅批注导出数据(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ").xls";
            //ExportExcelUtil
            ExportExcelUtil exportExcelUtil = new ExportExcelUtil();
            //导出excel的操作
            exportExcelUtil.expordExcel(tableThNames,fieldCns,approves,fileName,response);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }

    /**
     * @MethodName: getInpatientNosByName
     * @Description: 动态搜索病案号集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getInpatientNosByName")
    @ResponseBody
    public String getInpatientNos(String inpatientNo,String name){
        try{
            List<CommomVo> commomVos = commomMapper.getInpatientNosByName(inpatientNo,name);
            Map<String,String> strs = new HashMap();
            if(null != commomVos && !commomVos.isEmpty()){
                for (CommomVo commomVo : commomVos) {
                    if (StringUtils.isNoneBlank(commomVo.getInpatientNo())) {
                        strs.put(commomVo.getInpatientNo(), commomVo.getName());
                    }
                }
            }
            return JSON.toJSONString(strs);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @MethodName: getNameByInpatientNo
     * @Description: 动态搜索患者集合
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2019-07-02
     * @UpdateUser: 曾文和
     * @UpdateDate: 2019-07-02
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("getNameByInpatientNo")
    @ResponseBody
    public String getNameByInpatientNo(String inpatientNo,String name){
        try{
            List<CommomVo> commomVos = commomMapper.getInpatientNosByName(inpatientNo,name);
            Map<String,String> strs = new HashMap();
            if(null != commomVos && !commomVos.isEmpty()){
                for (CommomVo commomVo : commomVos) {
                    if (StringUtils.isNoneBlank(commomVo.getName())) {
                        strs.put(commomVo.getInpatientNo(), commomVo.getName());
                    }
                }
            }
            return JSON.toJSONString(strs);
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
            return null;
        }
    }

    //批量添加174
    @RequestMapping(value="simpleAddApprove174",method = {RequestMethod.POST})
    @ResponseBody
    public ResponseEntity<String> simpleAddApprove174(HttpServletRequest request){
        OutputStream os = null;
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentType(new MediaType("text","html", Charset.forName("UTF-8")));
        try {
            //读取文件
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);
            MultipartFile multipartFile = multiRequest.getFile("upfile");
            String effeTime = request.getParameter("effeTime");
            String effeDays = request.getParameter("effeDays");
            String applyType = request.getParameter("applyType");
            String applyReason = request.getParameter("applyReason");
            //属性名
            String[] fieldNames = {"inpatientNo","name","admissTimes"};
            //判断集中类中的方法名
            String[] judgeMethods = {"judgeInpatientNo1","judgeName","judgeAdmissTimes"};
            Emr_Apply_Approve applyApprove = new Emr_Apply_Approve();
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Power_User user = (Power_User)request.getSession().getAttribute("CURRENT_USER");
            applyApprove.setApplyer(user.getUserName());
            applyApprove.setApplyTime(fmt.format(new Date()));
            applyApprove.setEffeTime(effeTime);
            applyApprove.setApplyState("2");
            if(StringUtils.isNotBlank(effeDays)){
                applyApprove.setEffeDays(Integer.valueOf(effeDays));
            }
            applyApprove.setApplyType(applyType);
            applyApprove.setApplyReason(applyReason);
            //实例化
            ImportExcelUtil.newInstance("emr_Apply_ApproveMapper",applyApprove, Emr_Apply_Approve.class);
            //导入excel的操作
            ImportExcelEntity excelEntity = ImportExcelUtil.fileImport(multipartFile,fieldNames,judgeMethods,"judgeRecord");
            if(excelEntity.getSuccessCount() == 0 && excelEntity.getWrongCount() == 0){
                //无数据
                return new ResponseEntity<String>("无数据!", responseHeaders, HttpStatus.OK);
            }
            if(excelEntity.getWrongCount() == 0){
                //成功
                return new ResponseEntity<String>(null, responseHeaders, HttpStatus.OK);
            }else{
                //有出错数据
                String msgStr = excelEntity.getWorkBookKey()+"@已成功导入"+excelEntity.getSuccessCount()+"条,失败"+excelEntity.getWrongCount()+"条,随后将导出错误记录!";
                //是确认提交情况下发送通知
                sendPowerApproveInterface(applyType,excelEntity.getSuccessCount());
                return new ResponseEntity<String>(msgStr, responseHeaders, HttpStatus.OK);
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            //抛异常
            return new ResponseEntity<String>(e.getMessage(), responseHeaders, HttpStatus.OK);
        }finally {
            try {
                os.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * @MethodName: selectNotApproveList
     * @Description: 查询未审批数量
     * @Param
     * @Return
     * @Author: 曾文和
     * @CreateDate: 2020-04-24
     * @UpdateUser: 曾文和
     * @UpdateDate: 2020-04-24
     * @UpdateRemark: 更新说明
     * @Version: 1.0
     */
    @RequestMapping("selectNotApproveList")
    @ResponseBody
    public void selectNotApproveList(){
        try {
            //查询未审批集合
            List<Emr_Apply_Approve> applyApproves = applyApproveMapper.selectCountByApproveStateIsNull();
            if (null != applyApproves && !applyApproves.isEmpty()) {
                //调用权限系统推送通知
                String applyTypeName = "申请";
                applyApproveService.sendNotice(applyTypeName,applyApproves.size());
            }
        }catch (Exception e){
            ExceptionPrintUtil.printException(e);
            e.printStackTrace();
        }
    }
}
