/**
 * Copyright (C), 2015-2019
 * Author:   HJL
 * Date:     2019/7/19 15:43
 * Description:缺陷管理
 */
package com.emr.service.ipml;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emr.dao.Archive_Master_FollowingMapper;
import com.emr.dao.Emr_Fault_DetailMapper;
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.vo.Power_User_Dto;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class Emr_Fault_DetailServiceImpl implements Emr_Fault_DetailService {

    @Value("${backFee}")
    private String backFee;

    @Autowired
    private Emr_Fault_DetailMapper emrFaultDetailMapper;

    @Autowired
    private Emr_Fault_TypeService emrFaultTypeService;

    @Autowired
    private Emr_DictionaryService emrDictionaryService;

    @Autowired
    private PowerUserService powerUserService;
    @Autowired
    private Archive_Master_FollowingMapper archiveMasterFollowingMapper;
    /**
     * 根据条件查询缺陷列表
     * @param emrFaultVo
     * @return
     */
    @Override
    public OffsetLimitPage selectByCol(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        //return emrFaultDetailMapper.selectByCol(emrFaultDetail);
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list = emrFaultDetailMapper.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++) {
            //替换科室
            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);
                }
            }

            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);
                    }
                }
            }
        }

        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Emr_Fault_Vo> selectByCol(Emr_Fault_Vo emrFaultVo) {
        return emrFaultDetailMapper.selectByCol(emrFaultVo);
    }

    @Override
    public int updateCloByPrimaryKey(Emr_Fault_Detail emrFaultDetail) {
        return emrFaultDetailMapper.updateCloByPrimaryKey(emrFaultDetail);
    }

    @Override
    public Emr_Fault_Detail selectByArchiveDetailId(Emr_Fault_Detail emrFaultDetail) {
        return emrFaultDetailMapper.selectByArchiveDetailId(emrFaultDetail);
    }

    @Override
    public int insertSel(Emr_Fault_Detail record) {
        return emrFaultDetailMapper.insertSel(record);
    }

    @Override
    public List<Emr_Fault_Vo> selectByColumn(Emr_Fault_Detail emrFaultDetail) {
        List<Emr_Fault_Vo> list=emrFaultDetailMapper.selectByColumn(emrFaultDetail);
        if(list!=null && list.size()>0){
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Emr_Fault_Vo emrFaultVo : list) {
                if (null != powerUserList) {
                    //获取处理人
                    String dealPerson = emrFaultVo.getDealPerson();

                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(dealPerson) && powerUserDto.getUserName().equals(dealPerson)) {
                            emrFaultVo.setDealPerson(name);
                        }

                    }
                }
            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage selectByColumn(Emr_Fault_Detail emrFaultDetail, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list = emrFaultDetailMapper.selectByColumn(emrFaultDetail);
        if(list!=null && list.size()>0){
            //查询用户集合
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<Power_User_Dto> powerUserList = null;
            if (!CollectionUtils.isEmpty(powerUsers)) {
                //转换对象
                powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), Power_User_Dto.class);
            }
            //遍历赋值
            for (Emr_Fault_Vo emrFaultVo : list) {
                if (null != powerUserList) {
                    //获取处理人
                    String dealPerson = emrFaultVo.getDealPerson();

                    //遍历匹配工号赋值姓名
                    for (Power_User_Dto powerUserDto : powerUserList) {
                        String name = powerUserDto.getName();
                        if (StringUtils.isNotBlank(dealPerson) && powerUserDto.getUserName().equals(dealPerson)) {
                            emrFaultVo.setDealPerson(name);
                        }

                    }
                }
            }
        }
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public int deleteById(Integer id) {
        return emrFaultDetailMapper.deleteById(id);
    }

    @Override
    public int delByArchiveId(Emr_Fault_Detail record) {
        return emrFaultDetailMapper.delByArchiveId(record);
    }

    @Override
    public int delbyCol(Emr_Fault_Detail record) {
        return emrFaultDetailMapper.delbyCol(record);
    }

    @Override
    public Emr_Fault_Detail selectById(Integer id) {
        return emrFaultDetailMapper.selectById(id);
    }

    @Override
    public Emr_Fault_Detail selectByDept(Emr_Fault_Detail emrFaultDetail) {
        return emrFaultDetailMapper.selectByDept(emrFaultDetail);
    }

    @Override
    public List<Emr_Fault_Detail> selectByArchiveId(Emr_Fault_Detail emrFaultDetail) {
        return emrFaultDetailMapper.selectByArchiveId(emrFaultDetail);
    }

    @Override
    public OffsetLimitPage selectStorageByCol(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        //return emrFaultDetailMapper.selectByCol(emrFaultDetail);
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list = emrFaultDetailMapper.selectStorageByCol(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++) {
            //替换科室
            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())){
                    //入院科室dept_admission_to
                    dept2 = dept2.replace(dept2, dicList.get(k).getName());
                    list.get(i).setDeptAdmissionTo(dept2);
                }
            }

            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);
                    }
                }
            }
        }

        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Emr_Fault_Vo> selectStorageByCol(Emr_Fault_Vo emrFaultVo) {
        return emrFaultDetailMapper.selectStorageByCol(emrFaultVo);
    }

    @Override
    public List<Emr_Fault_Vo> getQualityControlList(Emr_Fault_Vo emrFaultVo) {
        return emrFaultDetailMapper.getQualityControlList(emrFaultVo);
    }

    @Override
    public OffsetLimitPage getQualityControlList(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list = emrFaultDetailMapper.getQualityControlList(emrFaultVo);

        JSONArray powerUsers = powerUserService.getPowerUserList("1");
        List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
        if (powerUserList != null){
            Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                @Override
                public String apply(JSONObject temp) {
                    return temp.getString("userName");
                }});

            for (Emr_Fault_Vo emr_fault_vo : list) {

                JSONObject userInfo = mappedMovies.get(emr_fault_vo.getDoctorInCharge());
                if (userInfo==null){
                    emr_fault_vo.setDoctorInCharge(emr_fault_vo.getDoctorInCharge());
                }else {
                    emr_fault_vo.setDoctorInCharge(userInfo.getString("name"));
                }

                userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                if (userInfo==null){
                    emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                }else {
                    emr_fault_vo.setCreater(userInfo.getString("name"));
                }
            }

        }
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Emr_Fault_Vo> masterTotalList(Emr_Fault_Vo emrFaultVo) {
        //获取病案信息
        String priceVal="";
        if(backFee!=null && backFee!=""){
            priceVal=backFee;
        }else{
            //默认退回一次扣30元
            priceVal="30";
        }
        emrFaultVo.setBackFee(backFee);
        List<Emr_Fault_Vo> list= emrFaultDetailMapper.masterTotalList(emrFaultVo);
        if(list!=null && list.size()>0) {
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            if (powerUserList != null){
                Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                    @Override
                    public String apply(JSONObject temp) {
                        return temp.getString("userName");
                    }});

                for (Emr_Fault_Vo emr_fault_vo : list) {
                  //  emr_fault_vo.setBackFee(priceVal);
                    //主管医生
                    JSONObject userInfo = mappedMovies.get(emr_fault_vo.getDoctorInCharge());
                    if (userInfo == null) {
                        emr_fault_vo.setDoctorInCharge(emr_fault_vo.getDoctorInCharge());
                    } else {
                        emr_fault_vo.setDoctorInCharge(userInfo.getString("name"));
                    }
                    //退回人
                    userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                    if (userInfo == null) {
                        emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                    } else {
                        emr_fault_vo.setCreater(userInfo.getString("name"));
                    }
                }

            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage masterTotalList(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list =masterTotalList(emrFaultVo);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Emr_Fault_Vo> faultBackScoreList(Emr_Fault_Vo emrFaultVo) {
        List<Emr_Fault_Vo> list= emrFaultDetailMapper.faultBackScoreList(emrFaultVo);
        if(list!=null && list.size()>0){
            Archive_Master_Following archiveMasterFollowing=new Archive_Master_Following();
            archiveMasterFollowing.setFollowingType("9");
            if(StringUtils.isNotBlank(emrFaultVo.getArchiveDetailId())){
                archiveMasterFollowing.setMasterId(emrFaultVo.getArchiveDetailId());
            }
            //根据条件查询跟随流程记录的退回次数排序列表，remark暂存退回次数
            List<Archive_Master_Following> followList =archiveMasterFollowingMapper.selByCol(archiveMasterFollowing);
            List<Archive_Master_Following> followList2=null;
            if(followList!=null && followList.size()>0){
                //Boolean bol=false;
                JSONArray powerUsers = powerUserService.getPowerUserList("1");
                List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
                if (powerUserList != null){
                    Map<String,JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject,String>() {
                        @Override
                        public String apply(JSONObject temp) {
                            return temp.getString("userName");
                        }});
                    for (Emr_Fault_Vo emr_fault_vo : list) {
                        if(StringUtils.isNotBlank(emr_fault_vo.getCreater())) {
                            JSONObject userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                            if (userInfo == null) {
                                emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                            } else {
                                emr_fault_vo.setCreater(userInfo.getString("name"));
                            }
                        }
                        followList2= followList.stream().filter(u -> (u.getMasterId()).equals(emr_fault_vo.getArchiveDetailId()) && u.getHandleTime()!=null && u.getHandleTime()!="").collect(Collectors.toList());
                        //退回次数
                        for(int i=0;i<followList2.size();i++){
                            if(emr_fault_vo.getArchiveDetailId().equals(followList2.get(i).getMasterId()) && emr_fault_vo.getCreateTime()!=null && emr_fault_vo.getCreateTime()!="" && followList2.get(i).getHandleTime()!=null && followList2.get(i).getHandleTime()!="") {
                                //a早于b返回true
                                try {
                                    if (compare(emr_fault_vo.getCreateTime(), followList2.get(i).getHandleTime())) {
                                        emr_fault_vo.setBackNum(followList2.get(i).getRemark());
                                        if(followList2.get(i).getRemark().equals("1")){
                                            //第一次签收
                                            emr_fault_vo.setStartDateTo("2000-01-01 01:00:00");
                                            emr_fault_vo.setEndDateTo(followList2.get(i).getHandleTime());
                                        }else{
                                            emr_fault_vo.setStartDateTo(followList2.get(i - 1).getHandleTime());
                                            if (StringUtils.isNotBlank(followList2.get(i).getHandleTime())) {
                                                emr_fault_vo.setEndDateTo(followList2.get(i).getHandleTime());
                                            } else {
                                                emr_fault_vo.setEndDateTo(followList2.get(i - 1).getHandleTime());
                                            }
                                        }
                                        break;
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }else{
                                emr_fault_vo.setBackNum("异常");
                            }
                        }
                    }
                }
            }else{
                //跟随流程表必须有病案室退回科主任记录，否则list为空
                list=null;
            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage faultBackScoreList(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list =faultBackScoreList(emrFaultVo);
        return new OffsetLimitPage((Page) list);
    }

    @Override
    public List<Emr_Fault_Vo> selByCol(Emr_Fault_Vo emrFaultVo) {
        List<Emr_Fault_Vo> list=emrFaultDetailMapper.selByCol(emrFaultVo);
        if(list!=null && list.size()>0) {
            JSONArray powerUsers = powerUserService.getPowerUserList("1");
            List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
            if (powerUserList != null) {
                Map<String, JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject, String>() {
                    @Override
                    public String apply(JSONObject temp) {
                        return temp.getString("userName");
                    }
                });

                for (Emr_Fault_Vo emr_fault_vo : list) {
                    //创建人
                    JSONObject  userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                    if (userInfo == null) {
                        emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                    } else {
                        emr_fault_vo.setCreater(userInfo.getString("name"));
                    }


                    userInfo = mappedMovies.get(emr_fault_vo.getDoctorInCharge());
                    if (userInfo == null) {
                        emr_fault_vo.setDoctorInCharge(emr_fault_vo.getDoctorInCharge());
                    } else {
                        emr_fault_vo.setDoctorInCharge(userInfo.getString("name"));
                    }
                }
            }
        }
        return list;
    }

    @Override
    public OffsetLimitPage selByCol(Emr_Fault_Vo emrFaultVo, Integer offset, Integer limit) {
        PageHelper.offsetPage(offset, limit);
        List<Emr_Fault_Vo> list = emrFaultDetailMapper.selByCol(emrFaultVo);
        if(list!=null && list.size()>0) {
           JSONArray powerUsers = powerUserService.getPowerUserList("1");
           List<JSONObject> powerUserList = JSONArray.parseArray(powerUsers.toJSONString(), JSONObject.class);
           if (powerUserList != null) {
               Map<String, JSONObject> mappedMovies = Maps.uniqueIndex(powerUserList, new Function<JSONObject, String>() {
                   @Override
                   public String apply(JSONObject temp) {
                       return temp.getString("userName");
                   }
               });

               for (Emr_Fault_Vo emr_fault_vo : list) {
                   //创建人
                   JSONObject userInfo = mappedMovies.get(emr_fault_vo.getCreater());
                   if (userInfo == null) {
                       emr_fault_vo.setCreater(emr_fault_vo.getCreater());
                   } else {
                       emr_fault_vo.setCreater(userInfo.getString("name"));
                   }
               }
           }
        }
        return new OffsetLimitPage((Page) 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;
        }
    }
}
 

