/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 14:38
 * Description:出院浏览
 */
package com.emr.controller;

import com.emr.entity.*;
import com.emr.service.*;
import com.emr.util.IDHelper;
import com.emr.util.ThreadExcelUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
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.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/beHosp")
public class beHospitaledController {
    @Autowired
    private Archive_MasterService archiveMasterService;

    @Autowired
    private Emr_Fault_DetailService emrFaultDetailService;

    @Autowired
    private Emr_Staff_RemarkService emrStaffRemarkService;

    @Autowired
    private Sign_ListService signListService;

    @Autowired(required = false)
    private Archive_Master_FollowingService archive_master_followingService;

    @Value("${HomepageDictionary}")
    private String HomepageDictionary;
    @Value("${HomepageMethod}")
    private String HomepageMethod;


    @RequestMapping(value = "/beHosps")
    public String inHospitals(Model model) {
        //return "beHospitaledDir/beHospListNow";
        return "beHospitaledDir/beHospList";
    }

    @ResponseBody
    @RequestMapping(value = "/beHospList")
    public OffsetLimitPage beHospList(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo, Integer offset, Integer limit) {
        OffsetLimitPage result = archiveMasterService.selectByColumn(archiveMasterVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id","住院号","住院次数","名字","性别","身份证","出院科室","出院日期","主管医生","状态","医生是否提交","医生","医生提交日期","护士是否提交","护士","护士提交日期","电子病历医生提交","电子病历护士提交","是否死亡"};
        String[] fileNames = {"id","inpNo","visitId","name","sex","idNo","deptName","dischargeDateTime","doctorInCharge","archivestate","cmtDoctor","doctorName","cmtDoctorDate","cmtNurse","nurseName","cmtDurseDate","emrDoctorCmt","emrNureCmt","deathFlag"};
        //文件名
        String fileName = "出院浏览" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据beHospList
        List<Archive_Master_Vo> list = archiveMasterService.selectByColumn(archiveMasterVo);
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
    }

    @ResponseBody
    @RequestMapping(value = "/wzByArchivId")
    public String wzByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) {
        String result = "";
        try {
            String endpoint = HomepageDictionary;
            //String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";
            String method = HomepageMethod;
            JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
            Client client = factory.createClient(endpoint);
            String temp = emrFaultDetail.getArchiveDetailId();
            Object[] res = null;
            res = client.invoke(method, temp);
            result = (String) res[0];
            //给方法传递参数，并且调用方法
            //System.out.println("result is " + result);
            //保存到数据库
            Archive_Master obj=archiveMasterService.selectById(temp);
            if(obj!=null) {
                obj.setLockinfo(result+"");
                //保存完整性内容
                archiveMasterService.updateByClo(obj);
            }
        } catch (Exception e) {
            System.err.println(e.toString());
            return "连接不到完整性接口!";
        }
        return result+"";
    }

    @ResponseBody
    @RequestMapping(value = "/updateStateByArchivId")
    public String updateStateByArchivId(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) {
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format1.format(new Date());
        String result = "";
        Emr_Fault_Detail entityFault=new Emr_Fault_Detail();
        entityFault.setArchiveDetailId(emrFaultDetail.getArchiveDetailId());
        List<Emr_Fault_Detail> faultList=emrFaultDetailService.selectByArchiveId(entityFault);
        int flagNum=0;
        if(faultList!=null && faultList.size()>0){
            //获取未处理缺陷数量
            for (int k = 0; k < faultList.size(); k++) {
                if ("1".equals(faultList.get(k).getBackFlag()) || "5".equals(faultList.get(k).getBackFlag())) {
                    flagNum+=1;
                }
            }
        }
        if(flagNum==0) {
            try {
                String endpoint = HomepageDictionary;
                //String endpoint = "http://localhost:8080/ca3/services/caSynrochnized?wsdl";
                String method = HomepageMethod;
                JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
                Client client = factory.createClient(endpoint);
                String temp = emrFaultDetail.getArchiveDetailId();
                Object[] res = null;
                res = client.invoke(method, temp);
                result = (String) res[0];
                //给方法传递参数，并且调用方法
                //System.out.println("result is " + result);
            } catch (Exception e) {
                System.err.println(e.toString());
                return "连接不到完整性接口!";
            }
            if (result.equals("完整")) {
                //修改病案归档状态
                Archive_Master archiveMaster = new Archive_Master();
                archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
                archiveMaster.setArchivestate(emrFaultDetail.getState());
                archiveMaster.setLockinfo(result);
                archiveMaster.setCmtDoctor(1);
                archiveMaster.setCmtNurse(1);
                int bol = archiveMasterService.updateByClo(archiveMaster);

                //添加初审内容
                if (bol == 1) {
                    //参数输入
                    archiveMaster.setFirstInstance(username);
                    emrFaultDetail.setCreater(username);
                    emrFaultDetail.setCreateTime(nowTime);
                    emrFaultDetail.setState("未召回");
                    bol = emrFaultDetailService.insertSel(emrFaultDetail);

                    //初审成功日志
                    String handleName = user.getUserPosition();//姓名
                    Archive_Master_Following archive_master_following = new Archive_Master_Following();
                    archive_master_following.setMasterId(emrFaultDetail.getArchiveDetailId());
                    //following表中添加科主任审核操作记录
                    archive_master_following.setFollowingType("5");
                    archive_master_following.setFollowingContent("科主任审核");
                    archive_master_following.setHandleTime(nowTime);
                    archive_master_following.setHandleId(username);
                    archive_master_following.setHandleName(handleName);
                    archive_master_followingService.insertSelective(archive_master_following);
                }
            } else {
                //修改病案归档完整内容Lockinfo
                Archive_Master archiveMaster = new Archive_Master();
                emrFaultDetail.setCreater(username);
                emrFaultDetail.setCreateTime(nowTime);
                archiveMaster.setFirstInstance(username);
                //archiveMaster.setArchivestate(emrFaultDetail.getState());
                archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
                archiveMaster.setLockinfo("强制提交，" + result);
                archiveMaster.setCmtDoctor(1);
                archiveMaster.setCmtNurse(1);
                archiveMasterService.updateByClo(archiveMaster);
            }
        }else{
            result = "提交失败,存在缺陷未处理!";
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/forceWZ")
    public String forceWZ(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) {
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format1.format(new Date());
        //修改病案归档状态
        Archive_Master archiveMaster = new Archive_Master();
        archiveMaster.setId(emrFaultDetail.getArchiveDetailId());
        archiveMaster.setArchivestate("初审");
        archiveMaster.setCmtDoctor(1);
        archiveMaster.setCmtNurse(1);
        archiveMaster.setFirstInstance(username);
        archiveMaster.setLockinfo(emrFaultDetail.getContent());
        int bol = archiveMasterService.updateByClo(archiveMaster);
        if(bol==1) {
            emrFaultDetail.setCreater(username);
            emrFaultDetail.setCreateTime(nowTime);
            emrFaultDetail.setArchiveState("初审");
            bol = emrFaultDetailService.insertSel(emrFaultDetail);
            //添加初审内容
            if (bol == 1) {
                //参数输入
                emrFaultDetail.setState("未召回");
                emrFaultDetail.setArchiveState(null);
                bol = emrFaultDetailService.insertSel(emrFaultDetail);
            }
            //初审成功日志
            String handleName = user.getUserPosition();//姓名
            Archive_Master_Following archive_master_following = new Archive_Master_Following();
            archive_master_following.setMasterId(emrFaultDetail.getArchiveDetailId());
            //following表中添加科主任审核操作记录
            archive_master_following.setFollowingType("5");
            archive_master_following.setFollowingContent("科主任审核");
            archive_master_following.setHandleTime(nowTime);
            archive_master_following.setHandleId(username);
            archive_master_following.setHandleName(handleName);
            archive_master_followingService.insertSelective(archive_master_following);
        }
        return bol+"";
    }

    @ResponseBody
    @RequestMapping(value = "/getMaster")
    public  Archive_Master selectById(HttpServletRequest request, HttpServletResponse response, Archive_Master archiveMaster){
        Archive_Master obj =new Archive_Master();
        //判断id 不为空
        if (!archiveMaster.getId().equals("") && !archiveMaster.equals(null)) {
            obj = archiveMasterService.selectById(archiveMaster.getId());
        }
        return obj;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/cmtDoctorOrNurs")
    public String cmtDoctorOrNurs(HttpServletRequest request, HttpServletResponse response, Archive_Master_Vo archiveMasterVo) throws Exception {
        response.setCharacterEncoding("utf-8");
        // 从session获取用户名
        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//获取前面登录的用户名
        String handleName = user.getUserPosition();
        Archive_Master archiveMaster=new Archive_Master();
        archiveMaster.setId(archiveMasterVo.getId());
        archiveMaster.setCmtDoctor(archiveMasterVo.getCmtDoctor());
        archiveMaster.setCmtNurse(archiveMasterVo.getCmtNurse());

        Emr_Staff_Remark emrStaffRemark=new Emr_Staff_Remark();
        emrStaffRemark.setEffective(1);
        emrStaffRemark.setMasterId(archiveMasterVo.getId());
        emrStaffRemark.setContent(archiveMasterVo.getContent());

        Archive_Master_Following archive_master_following = new Archive_Master_Following();
        archive_master_following.setMasterId(archiveMasterVo.getId());

        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format1.format(new Date());
        String result="";
        int bol =0;
        //判断id 不为空
        if(!archiveMaster.getId().equals("")&&!archiveMaster.equals(null)) {
            Archive_Master obj=archiveMasterService.selectById(archiveMaster.getId());
            if(obj!=null) {
                //如果是医生提交判断医生是否有缺陷未处理，如果是护士提交判断护士是否有缺陷未处理
                //查询该病案号缺陷，如果有医生就退回医生如果有护士则退回护士否则不退回提示
                Emr_Fault_Detail entityFault=new Emr_Fault_Detail();
                entityFault.setArchiveDetailId(archiveMaster.getId());
                List<Emr_Fault_Detail> faultList=emrFaultDetailService.selectByArchiveId(entityFault);
                int doctorFlagNum=0;
                int nurseFlagNum=0;
                if(faultList!=null && faultList.size()>0){
                    //1医生 ，2护士
                    for (int k = 0; k < faultList.size(); k++) {
                        if ("1".equals(faultList.get(k).getBackFlag()) || "5".equals(faultList.get(k).getBackFlag())) {
                            doctorFlagNum+=1;
                        }
                        if ("2".equals(faultList.get(k).getBackFlag()) || "6".equals(faultList.get(k).getBackFlag())) {
                            nurseFlagNum+=1;
                        }
                    }
                }

                //修改病案归档状态
                if (archiveMaster.getCmtDoctor()==1) {
                    if(doctorFlagNum==0) {
                        //医生提交（医生和护士同时提交后，归档状态变更为：提交）
                        if (obj.getCmtNurse() == 1) {
                            archiveMaster.setArchivestate("提交");
                            archiveMaster.setCmtNurse(1);
                        }
                        archiveMaster.setCmtDoctor(1);
                        archiveMaster.setDoctorName(username);
                        archiveMaster.setCmtDoctorDate(nowTime);

                        //添加医生备注记录
                        emrStaffRemark.setTypeFlag(0);
                        List<Emr_Staff_Remark> list = emrStaffRemarkService.selectByCol(emrStaffRemark);
                        if (list != null && list.size() > 0) {
                            //修改
                            list.get(0).setUpdateTime(nowTime);
                            list.get(0).setUpdater(username);
                            list.get(0).setContent(archiveMasterVo.getContent());
                            list.get(0).setUpdateTime(nowTime);
                            bol = emrStaffRemarkService.updateByClo(list.get(0));
                        } else {
                            //插入
                            emrStaffRemark.setCreater(username);
                            emrStaffRemark.setCreateTime(nowTime);
                            bol = emrStaffRemarkService.insertClo(emrStaffRemark);
                        }

                        //following表中添加归档医生提交操作记录
                        archive_master_following.setFollowingType("1");//followingType=1 归档医生提交
                        archive_master_following.setFollowingContent("主管医生提交");
                        archive_master_following.setHandleTime(nowTime);
                        archive_master_following.setHandleId(username);
                        archive_master_following.setHandleName(handleName);
                        bol = archive_master_followingService.insertSelective(archive_master_following);
                        //addArchiveOther(archiveMasterVo);
                    }else{
                        result = "医生提交失败,存在缺陷未处理!";
                    }
                } else if (archiveMaster.getCmtNurse()==1) {
                    if(nurseFlagNum==0) {
                        //护士提交（医生和护士同时提交后，归档状态变更为：提交）
                        if (obj.getCmtDoctor() == 1) {
                            archiveMaster.setArchivestate("提交");
                            archiveMaster.setCmtDoctor(1);
                        }
                        archiveMaster.setCmtNurse(1);
                        archiveMaster.setNurseName(username);
                        archiveMaster.setCmtNurseDate(nowTime);

                        //添加护士备注记录
                        emrStaffRemark.setTypeFlag(1);
                        List<Emr_Staff_Remark> list = emrStaffRemarkService.selectByCol(emrStaffRemark);
                        if (list != null && list.size() > 0) {
                            //修改
                            list.get(0).setUpdater(username);
                            list.get(0).setUpdateTime(nowTime);
                            list.get(0).setContent(archiveMasterVo.getContent());
                            bol = emrStaffRemarkService.updateByClo(list.get(0));
                        } else {
                            //插入
                            emrStaffRemark.setCreater(username);
                            emrStaffRemark.setCreateTime(nowTime);
                            bol = emrStaffRemarkService.insertClo(emrStaffRemark);
                        }

                        //following表中添加归档护士提交操作记录
                        archive_master_following.setFollowingType("3");
                        archive_master_following.setFollowingContent("护士长提交");
                        archive_master_following.setHandleTime(nowTime);
                        archive_master_following.setHandleId(username);
                        archive_master_following.setHandleName(handleName);
                        bol = archive_master_followingService.insertSelective(archive_master_following);
                    }else{
                        result = "护士提交失败,存在缺陷未处理!";
                    }
                }
                if(bol==1) {
                    archiveMaster.setIsscaned(archiveMasterVo.getIsscaned());
                    archiveMaster.setLockinfo(archiveMasterVo.getLockinfo());
                    bol = archiveMasterService.updateByClo(archiveMaster);
                    if(archiveMaster.getCmtDoctor()!=obj.getCmtDoctor()) {
                        result = "归档医生提交";
                    }else if(archiveMaster.getCmtNurse()!=obj.getCmtNurse()){
                        result = "归档护士提交";
                    }
                    if(bol==1){
                       result+="成功!";
                    }else{
                        result+= "失败!";
                    }
                }
            }else{
                result = "病案不存在!";
            }
        }else{
            result="病案不存在!";
        }
        return result;
    }


    @RequestMapping("getImg2")
    public void getImg2(HttpServletRequest request, HttpServletResponse response, String path) throws IOException {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(path);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/getDoctorInCharge")
    public List<Archive_Master> getDoctorInCharge(HttpServletResponse response, Archive_Master archiveMaster) throws Exception {
        //根据目前账号所在科室获取主管医生列表
        return archiveMasterService.getDoctorInCharge(archiveMaster);
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/withdrawDoctorOrNurs")
    public String withdrawDoctorOrNurs(HttpServletRequest request, HttpServletResponse response,Archive_Master_Vo archiveMasterVo) {
        response.setCharacterEncoding("utf-8");
        Archive_Master archiveMaster=new Archive_Master();
        archiveMaster.setId(archiveMasterVo.getId());
        archiveMaster.setCmtDoctor(archiveMasterVo.getCmtDoctor());
        archiveMaster.setCmtNurse(archiveMasterVo.getCmtNurse());

        Power_User user = (Power_User) request.getSession().getAttribute("CURRENT_USER");
        String username = user.getUserName();//工号
        String handleName = user.getUserPosition();//姓名
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = format1.format(new Date());

        String result="";
        int bol =0;
        //判断id 不为空
        if(!archiveMaster.getId().equals("") && !archiveMaster.getId().equals(null)) {
            Archive_Master obj = archiveMasterService.selectById(archiveMaster.getId());
            if (obj!=null){
                Archive_Master_Following archive_master_following = new Archive_Master_Following();
                archive_master_following.setMasterId(archiveMasterVo.getId());
                if (archiveMasterVo.getCmtDoctor()==0){
                    //医生撤回操作
                    archiveMaster.setCmtDoctorDate("");
                    archiveMaster.setDoctorName("");


                    //following表中添加归档医生撤回操作记录
                    archive_master_following.setFollowingType("2");
                    archive_master_following.setFollowingContent("主管医生撤回提交");
                    archive_master_following.setHandleTime(nowTime);
                    archive_master_following.setHandleId(username);
                    archive_master_following.setHandleName(handleName);
                    bol = archive_master_followingService.insertSelective(archive_master_following);
                    result="归档医生撤回成功!";
                }
                if (archiveMasterVo.getCmtNurse()==0){
                    //护士撤回操作
                    archiveMaster.setCmtNurseDate("");
                    archiveMaster.setNurseName("");

                    //following表中添加归档护士撤回操作记录
                    archive_master_following.setFollowingType("4");
                    archive_master_following.setFollowingContent("护士长撤回提交");
                    archive_master_following.setHandleTime(nowTime);
                    archive_master_following.setHandleId(username);
                    archive_master_following.setHandleName(handleName);
                    bol = archive_master_followingService.insertSelective(archive_master_following);
                    result="归档护士撤回成功!";
                }
                archiveMaster.setIsscaned(archiveMasterVo.getIsscaned());
                //撤回后，状态改为0
                archiveMaster.setIsscaned("0");
                bol=archiveMasterService.updateByClo(archiveMaster);
                if (bol!=1){
                    if (archiveMasterVo.getCmtDoctor()==0){
                        result="归档医生撤回失败!";
                    }
                    if (archiveMasterVo.getCmtNurse()==0){
                        result="归档护士撤回失败!";
                    }
                }
            }else{
                result = "病案不存在!";
            }
        }else{
            result="病案不存在!";
        }
        return result;
    }

    public void addArchiveOther(Archive_Master_Vo archiveMasterVo) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Archive_Master> master = archiveMasterService.selectByCol(archiveMasterVo);
        Sign_List signList = new Sign_List();
        if (master != null && master.size() > 0) {
            signList.setSysFlag(1);
            signList.setMasterID(master.get(0).getId());
            signList.setPid(master.get(0).getPatientId());

            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            signList.setC1((String) session.getAttribute("userSession"));
            signList.setC5("1");

            signList.setId(IDHelper.NewID());
            /*signList.setC2(master.get(0).getSigner());
            signList.setC3(master.get(0).getDeptName());*/
            signList.setCreatedtime(sdf.format(new Date()));
            signList.setdTime(sdf.format(new Date()));
            signList.setT1(sdf.format(new Date()));
            signListService.insertSignList(signList);
        }
    }
}
 

