/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 14:39
 * Description:缺陷管理
 */
package com.emr.controller;

import com.emr.entity.*;
import com.emr.service.Emr_DictionaryService;
import com.emr.service.Emr_Fault_DetailService;
import com.emr.service.Emr_Fault_TypeService;
import com.emr.util.ThreadExcelUtils;
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.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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("fault")
public class faultController {

    @Autowired
    private Emr_Fault_DetailService emrFaultDetailService;

    @Autowired
    private Emr_Fault_TypeService emrFaultTypeService;

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @RequestMapping(value = "/faults")
    public String faults(Model model) {
        return "faultDir/faultList";
    }

    @ResponseBody
    @RequestMapping(value = "/faultList")
    public OffsetLimitPage faultList(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        OffsetLimitPage result = emrFaultDetailService.selectByCol(emrFaultVo, offset, limit);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/exportExcel")
    public void exportExcel(HttpServletResponse response, Emr_Fault_Vo emrFaultVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = {"病历清单id","住院号","住院次数","姓名","出院科室","出院日期","归档状态","评分","回退内容","缺陷选项","缺陷内容","创建时间"};
        String[] fileNames = {"archiveDetailId","inpNo","visitId","name","deptName","dischargeDateTime","archivestate","score","backContent","assortId","content","createTime"};
        //文件名
        String fileName = "缺陷信息数据" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
        //构造excel的数据
        List<Emr_Fault_Vo> list = emrFaultDetailService.selectByCol(emrFaultVo);
        Emr_Dictionary dic = new Emr_Dictionary();
        dic.setEffective(1);
        dic.setTypecode("dept_code");
        //科室列表
        List<Emr_Dictionary> dicList = emrDictionaryService.dicByTypeCode(dic);
        //获取缺陷类别列表
        Emr_Fault_Type obj = new Emr_Fault_Type();
        obj.setEffective(1);
        //缺陷选项
        List<Emr_Fault_Type> typeLis = emrFaultTypeService.selectByCol(obj);
        for (int i = 0; i < list.size(); i++) {
            String assortId = list.get(i).getAssortId();
            if (assortId != "" && assortId != null) {
                String[] assorArr = assortId.split(",");
                //替换类别
                for (int j = 0; j < typeLis.size(); j++) {
                    String id = String.valueOf(typeLis.get(j).getId());
                    if (Arrays.asList(assorArr).contains(id)) {
                        assortId = assortId.replace(id, typeLis.get(j).getTypeName());
                        list.get(i).setAssortId(assortId);
                    }
                }
            }

            //替换科室
            for (int k = 0; k < dicList.size(); k++) {
                String deptName = list.get(i).getDeptName();
                //入院科室dept_admission_to
                String dept2 = list.get(i).getDeptAdmissionTo();
                if ((deptName != null && deptName.equals(dicList.get(k).getCode()))) {
                    //出院科室
                    deptName = deptName.replace(deptName, dicList.get(k).getName());
                    list.get(i).setDeptName(deptName);
                }
                if(dept2 != null && dept2.equals(dicList.get(k).getCode())) {
                    //入院科室
                    dept2 = dept2.replace(dept2, dicList.get(k).getName());
                    list.get(i).setDeptAdmissionTo(dept2);
                }
            }
        }
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
       /* System.out.println("开始执行导出.......");
        long start = System.currentTimeMillis();*/
        String result=utils.exportExcelToFilePath(response,utils.listConvert(list));
       /* long end = System.currentTimeMillis();
         System.out.println("耗时：" + (end - start) / 1000 + "秒");*/
    }


//    @ResponseBody
//    @RequestMapping(value = "/faultByArchiveId")
//    public Emr_Fault_Detail faultByArchiveId(HttpServletRequest request, HttpServletResponse response, String archiveDetailId) {
//        Emr_Fault_Detail result = emrFaultDetailService.selectByArchiveDetailId(archiveDetailId);
//        return result;
//    }

    @ResponseBody
    @RequestMapping(value = "/getFaultList")
    public List<Emr_Fault_Vo> getFaultList(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) {
        List<Emr_Fault_Vo> list = emrFaultDetailService.selectByColumn(emrFaultDetail);
        return list;
    }

    @ResponseBody
    @RequestMapping(value = "/getFaultPage")
    public OffsetLimitPage getFaultPage(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail, Integer offset, Integer limit) {
        OffsetLimitPage result = emrFaultDetailService.selectByColumn(emrFaultDetail, offset, limit);
        return result;
    }
    //bol = emrFaultDetailService.insertSel(emrFaultDetail);

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/addFaultList")
    public String addFaultList(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo) {
        response.setCharacterEncoding("utf-8");
        String result = "";

        // 从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());
        if (emrFaultVo.getArchiveDetailId() != null) {
            //判断是修改还是添加
            if (emrFaultVo.getId() != null) {

                //已存在删了，重新添加
                emrFaultDetailService.deleteById(emrFaultVo.getId());

            }
            //添加
            if (!(emrFaultVo.getBackFlag()).equals(null) && !emrFaultVo.getBackFlag().equals("")) {
                //判断是医生还是护士
                String roleVal = emrFaultVo.getBackFlag();
                if (roleVal.indexOf(",") != -1) {
                    Emr_Fault_Detail emrFaultDetail = new Emr_Fault_Detail();
                    emrFaultDetail.setCreater(username);
                    emrFaultDetail.setCreateTime(nowTime);
                    emrFaultDetail.setArchiveDetailId(emrFaultVo.getArchiveDetailId());
                    emrFaultDetail.setContent(emrFaultVo.getContent());
                    emrFaultDetail.setDealFlag("0");
                    //医生和护士
                    String[] arr = roleVal.split(",");
                    for (int j = 0; j < arr.length; j++) {
                        emrFaultDetail.setBackFlag(arr[j]);
                        //缺陷类别
                        if (emrFaultVo.getAssortId() != null && emrFaultVo.getAssortId() != "") {
                            if ((emrFaultVo.getAssortId()).indexOf(",") != -1) {
                                int bol = 0;
                                int sum = 0;
                                String[] assortArr = (emrFaultVo.getAssortId()).split(",");
                                String[] priceArr = (emrFaultVo.getBackContent()).split(",");
                                //多个缺陷循环插入数据
                                for (int i = 0; i < assortArr.length; i++) {
                                    String assrotId = assortArr[i];
                                    Emr_Fault_Type emrFaultType = emrFaultTypeService.selectById(Integer.valueOf(assrotId));
                                    emrFaultDetail.setMinusPoint(emrFaultType.getPrice());
                                    emrFaultDetail.setAssortId(assrotId);
                                    if (priceArr[i] != null && priceArr[i] != "") {
                                        BigDecimal price = new BigDecimal(priceArr[i]);
                                        emrFaultDetail.setPrice(price);
                                    }
                                    //医生或护士
                                    bol = emrFaultDetailService.insertSel(emrFaultDetail);
                                    if (bol == 1) {
                                        sum++;
                                    }
                                }
                                //判断bol次数和插入次数的和
                                if (sum == assortArr.length) {
                                    result = "保存成功!";
                                } else {
                                    result = "保存失败!";
                                }

                            } else {
                                Emr_Fault_Type emrFaultType = emrFaultTypeService.selectById(Integer.valueOf(emrFaultVo.getAssortId()));
                                emrFaultDetail.setMinusPoint(emrFaultType.getPrice());
                                emrFaultDetail.setAssortId(emrFaultVo.getAssortId());
                                if (emrFaultVo.getBackContent() != null && emrFaultVo.getBackContent() != "") {
                                    BigDecimal price = new BigDecimal(emrFaultVo.getBackContent());
                                    emrFaultDetail.setPrice(price);
                                }
                                //医生或护士
                                int bol = emrFaultDetailService.insertSel(emrFaultDetail);
                                if (bol == 1) {
                                    result = "保存成功!";
                                } else {
                                    result = "保存失败!";
                                }
                            }
                        } else {
                            result = "无缺陷项!";
                        }
                    }

                } else {
                    Emr_Fault_Detail emrFaultDetail = new Emr_Fault_Detail();
                    //参数输入
                    emrFaultDetail.setBackFlag(roleVal);
                    emrFaultDetail.setCreater(username);
                    emrFaultDetail.setCreateTime(nowTime);
                    emrFaultDetail.setArchiveDetailId(emrFaultVo.getArchiveDetailId());
                    emrFaultDetail.setContent(emrFaultVo.getContent());
                    emrFaultDetail.setDealFlag("0");
                    //缺陷类别
                    if (emrFaultVo.getAssortId() != null && emrFaultVo.getAssortId() != "") {
                        if ((emrFaultVo.getAssortId()).indexOf(",") != -1) {
                            int bol = 0;
                            int sum = 0;
                            String[] assortArr = (emrFaultVo.getAssortId()).split(",");
                            String[] priceArr = (emrFaultVo.getBackContent()).split(",");
                            //多个缺陷循环插入数据
                            for (int i = 0; i < assortArr.length; i++) {
                                String assrotId = assortArr[i];
                                Emr_Fault_Type emrFaultType = emrFaultTypeService.selectById(Integer.valueOf(assrotId));
                                emrFaultDetail.setMinusPoint(emrFaultType.getPrice());
                                emrFaultDetail.setAssortId(assrotId);
                                if (priceArr[i] != null && priceArr[i] != "") {
                                    BigDecimal price = new BigDecimal(priceArr[i]);
                                    emrFaultDetail.setPrice(price);
                                }
                                //医生或护士
                                bol = emrFaultDetailService.insertSel(emrFaultDetail);
                                if (bol == 1) {
                                    sum++;
                                }
                            }
                            //判断bol次数和插入次数的和
                            if (sum == assortArr.length) {
                                result = "保存成功!";
                            } else {
                                result = "保存失败!";
                            }

                        } else {
                            Emr_Fault_Type emrFaultType = emrFaultTypeService.selectById(Integer.valueOf(emrFaultVo.getAssortId()));
                            emrFaultDetail.setMinusPoint(emrFaultType.getPrice());
                            emrFaultDetail.setAssortId(emrFaultVo.getAssortId());
                            if (emrFaultVo.getBackContent() != null && emrFaultVo.getBackContent() != "") {
                                BigDecimal price = new BigDecimal(emrFaultVo.getBackContent());
                                emrFaultDetail.setPrice(price);
                            }
                            //医生或护士
                            int bol = emrFaultDetailService.insertSel(emrFaultDetail);
                            if (bol == 1) {
                                result = "保存成功!";
                            } else {
                                result = "保存失败!";
                            }
                        }
                    } else {
                        result = "无缺陷项!";
                    }


                }
            } else {
                result = "退回角色不为空!";
            }

        } else {
            result = "病案不存在!";
        }


        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/delFault")
    public String delFault(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo) {
        response.setCharacterEncoding("utf-8");
        String result = "";
        //判断是修改还是添加
        if (emrFaultVo.getId() != null) {
            //已存在删了，重新添加
           int bol= emrFaultDetailService.deleteById(emrFaultVo.getId());
           if(bol==1){
               result="删除成功!";
           }else{
               result="删除失败!";
           }
        }
        return result;
    }

    @Transactional
    @ResponseBody
    @RequestMapping(value = "/dealFault")
    public String dealFault(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo) {
        response.setCharacterEncoding("utf-8");
        String result = "";
        int bol =0;
        // 从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());
        //判断id是否为空
        if (emrFaultVo.getId() != null) {
            //已存在获取改条记录
            Emr_Fault_Detail entity=emrFaultDetailService.selectById(emrFaultVo.getId());
            if(entity!=null){
                //修改为已处理或未处理
                 if (entity.getDealFlag().equals("0")) {
                    entity.setDealFlag("1");
                    entity.setDealPerson(username);
                    entity.setDealTime(nowTime);

                } else if(entity.getDealFlag().equals("1")) {
                     entity.setDealFlag("0");
                     entity.setDealPerson("");
                     entity.setDealTime("");
                }
                //修改
                bol = emrFaultDetailService.updateCloByPrimaryKey(entity);
                if (bol == 1) {
                    result = "操作成功!";
                } else {
                    result = "操作失败!";
                }
            }else{
                result="不存在该缺陷记录!";
            }

        }else{
            result = "不存在该缺陷记录!";
        }
        return result;
    }


    @ResponseBody
    @RequestMapping(value = "/getTotal")
    public Emr_Fault_Detail getTotal(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Detail emrFaultDetail) {

        emrFaultDetail = emrFaultDetailService.selectByDept(emrFaultDetail);
        return emrFaultDetail;
    }

    @ResponseBody
    @RequestMapping(value = "/getQualityControlList")
    public OffsetLimitPage getQualityControlList(HttpServletRequest request, HttpServletResponse response, Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        OffsetLimitPage result = emrFaultDetailService.getQualityControlList(emrFaultVo, offset, limit);
        return result;
    }
}
 

