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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.service.PowerUserService;
import com.emr.util.ThreadExcelUtils;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
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.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@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";
    }


    @RequestMapping(value = "/faultScores")
    public String faultScores(Model model) {
        return "faultScoreDir/faultScoreList";
    }

    /*@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 = new String[]{"病历清单id", "住院号", "住院次数", "姓名", "出院科室", "出院日期", "归档状态", "评分", "主管医生", "退回总次数", "退回总费用(元)", "当前退回次数", "退回费用", "退回人", "退回时间", "缺陷选项", "缺陷评分", "缺陷内容", "创建人", "创建时间"};
        String[] fileNames = new String[]{"archiveDetailId", "inpNo", "visitId", "name", "deptName", "dischargeDateTime", "archivestate", "score", "doctorInCharge", "totalBackNum", "totalBackFee", "backNum", "backFee", "updater", "updateTime", "assortName", "price", "content", "creater", "createTime"};
        String fileName = "缺陷信息数据" + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()) + ".xls";
        List<Emr_Fault_Vo> list = this.emrFaultDetailService.selByCol(emrFaultVo);
        List<Emr_Fault_Vo> backList = this.emrFaultDetailService.faultBackScoreList(emrFaultVo);
        List<Emr_Fault_Vo> masterList = this.emrFaultDetailService.masterTotalList(emrFaultVo);
        if (list != null && list.size() > 0 && backList != null && backList.size() > 0 && masterList != null && masterList.size() > 0) {
            Iterator var9 = list.iterator();
            label88:
            while(true) {
                label86:
                while(true) {
                    if (!var9.hasNext()) {
                        break label88;
                    }

                    Emr_Fault_Vo faultInfo = (Emr_Fault_Vo)var9.next();
                    faultInfo.setBackFee("0");
                    faultInfo.setBackNum("0");
                    faultInfo.setUpdater((String)null);
                    faultInfo.setTotalBackNum("0");
                    faultInfo.setTotalBackFee("0");
                    List<Emr_Fault_Vo> masterList2 = (List)masterList.stream().filter((u) -> {
                        return u.getArchiveDetailId().equals(faultInfo.getArchiveDetailId());
                    }).collect(Collectors.toList());
                    if (masterList2.size() > 0) {
                        Emr_Fault_Vo masertInfo = (Emr_Fault_Vo)masterList2.get(0);
                        faultInfo.setBackFee(masertInfo.getBackFee());
                        faultInfo.setInpNo(masertInfo.getInpNo());
                        faultInfo.setVisitId(masertInfo.getVisitId());
                        faultInfo.setName(masertInfo.getName());
                        faultInfo.setDischargeDateTime(masertInfo.getDischargeDateTime());
                        faultInfo.setArchiveState(masertInfo.getArchiveState());
                        BigDecimal score = faultInfo.getScore();
                        Double  v = score.doubleValue();
                        if (v==0){
                            faultInfo.setScore(BigDecimal.valueOf(100.0));
                            faultInfo.setPrice(BigDecimal.valueOf(0));
                        }else {
                            double v1 = 100 - v;
                            faultInfo.setScore(BigDecimal.valueOf(v));
                            faultInfo.setPrice(BigDecimal.valueOf(v1));
                        }
                        faultInfo.setTotalBackNum(masertInfo.getTotalBackNum());
                        faultInfo.setTotalBackFee(masertInfo.getTotalBackFee());
                    } else {
                        faultInfo.setPrice(new BigDecimal(0));
                    }
                    List<Emr_Fault_Vo> backList2 = (List)backList.stream().filter((u) -> {
                        return u.getArchiveDetailId().equals(faultInfo.getArchiveDetailId());
                    }).collect(Collectors.toList());
                    Iterator var13 = backList2.iterator();
                    while(true) {
                        while(true) {
                            Emr_Fault_Vo backInfo;
                            do {
                                do {
                                    if (!var13.hasNext()) {
                                        continue label86;
                                    }

                                    backInfo = (Emr_Fault_Vo)var13.next();
                                } while(backInfo.getCreateTime() == null);
                            } while(backInfo.getCreateTime() == "");
                            if (backInfo.getStartDateTo() != null && backInfo.getStartDateTo() != "" && backInfo.getEndDateTo() != null && backInfo.getEndDateTo() != "") {
                                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                Date nowTime = ft.parse(faultInfo.getCreateTime());
                                Date startTime = ft.parse(backInfo.getStartDateTo());
                                Date endTime = ft.parse(backInfo.getEndDateTo());
                                if (isEffectiveDate(nowTime, startTime, endTime)) {
                                    faultInfo.setStartDateTo(backInfo.getStartDateTo());
                                    faultInfo.setEndDateTo(backInfo.getEndDateTo());
                                    faultInfo.setBackNum(backInfo.getBackNum());
                                    faultInfo.setUpdater(backInfo.getCreater());
                                    if (StringUtils.isNotBlank(backInfo.getEndDateTo())) {
                                        faultInfo.setUpdateTime(backInfo.getEndDateTo());
                                    } else {
                                        faultInfo.setUpdateTime(backInfo.getCreateTime());
                                    }

                                    faultInfo.setBackContent(backInfo.getContent());
                                    continue label86;
                                }
                            } else if (faultInfo.getEndDateTo() != null && faultInfo.getEndDateTo() != "") {
                                if (this.compare(backInfo.getCreateTime(), faultInfo.getEndDateTo())) {
                                    faultInfo.setBackNum(backInfo.getBackNum());
                                    faultInfo.setUpdater(backInfo.getCreater());
                                    if (StringUtils.isNotBlank(backInfo.getEndDateTo())) {
                                        faultInfo.setUpdateTime(backInfo.getEndDateTo());
                                    } else {
                                        faultInfo.setUpdateTime(backInfo.getCreateTime());
                                    }

                                    faultInfo.setBackContent(backInfo.getContent());
                                    continue label86;
                                }
                            } else if (faultInfo.getStartDateTo() != null && faultInfo.getStartDateTo() != "" && this.compare(faultInfo.getStartDateTo(), backInfo.getCreateTime())) {
                                faultInfo.setBackNum(backInfo.getBackNum());
                                faultInfo.setUpdater(backInfo.getCreater());
                                if (StringUtils.isNotBlank(backInfo.getEndDateTo())) {
                                    faultInfo.setUpdateTime(backInfo.getEndDateTo());
                                } else {
                                    faultInfo.setUpdateTime(backInfo.getCreateTime());
                                }

                                faultInfo.setBackContent(backInfo.getContent());
                                continue label86;
                            }
                        }
                    }
                }
            }
        }

        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        utils.exportExcelToFilePath(response, utils.listConvert(list));
    }

    @ResponseBody
    @RequestMapping(value = "/exportScoreExcel")
    public void exportScoreExcel(HttpServletResponse response, Emr_Fault_Vo emrFaultVo) throws Exception {
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        String[] header = new String[]{ "住院号", "住院次数", "姓名", "出院科室", "出院日期", "归档状态", "评分", "评分(等级)", "主管医生", "退回总次数","缺陷内容","缺陷自动内容","扣分","创建人"};
        String[] fileNames = new String[]{ "inpNo", "visitId", "name", "deptName", "dischargeDateTime", "archivestate", "score", "grade","doctorInCharge", "totalBackNum","typeName","priceTwo","creater"};
        String fileName = "病例评分" + (new SimpleDateFormat("yyyyMMddHHmmss")).format(new Date()) + ".xls";
        List<Emr_Fault_Vo> list = emrFaultDetailService.masterTotalScoreListExec(emrFaultVo);
        for (Emr_Fault_Vo lists:list){
            BigDecimal score = lists.getScore();
            if (score==null){
                BigDecimal num1 = new BigDecimal("100");
                lists.setScore(num1);
            }
        }
        ThreadExcelUtils utils = new ThreadExcelUtils(fileName, "", header, fileNames);
        utils.exportExcelToFilePath(response, utils.listConvert(list));
    }

    public boolean compare(String time1,String time2) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date a=sdf.parse(time1);
        Date b=sdf.parse(time2);
        //a早于b返回true
        if(a.before(b)){
            return  true;
        }else{
            return false;
        }
    }

    /**
     *
     * @param nowTime   当前时间
     * @param startTime	开始时间
     * @param endTime   结束时间
     * @return
     * @author sunran   判断当前时间在时间区间内
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
       // end.add(end.DATE,-1);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

//    @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);
                                    }
                                    emrFaultDetail.setPriceTwo(emrFaultType.getPriceTwo());
                                    //医生或护士
                                    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);
                                }
                                emrFaultDetail.setPriceTwo(emrFaultType.getPriceTwo());
                                //医生或护士
                                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);
                                }
                                emrFaultDetail.setPriceTwo(emrFaultType.getPriceTwo());
                                //医生或护士
                                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);
                            }
                            emrFaultDetail.setPriceTwo(emrFaultType.getPriceTwo());
                            //医生或护士
                            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;
    }


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



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

    }

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

    }

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


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

