package com.emr.service.emrPrintOrDownLoadInfo;

import com.emr.dao.CommomMapper;
import com.emr.dao.emrPrintAndDownLoad.EmrPrintDownloadInfoMapper;
import com.emr.entity.Power_User;
import com.emr.entity.emrPrintAndDownLoad.EmrPrintDownloadInfo;
import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo;
import com.emr.vo.commomSearch.ScanPathVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class PrintOrDownLoadInfoService {
    @Autowired
    private EmrPrintDownloadInfoMapper printDownloadInfoMapper;
    @Autowired
    private CommomMapper commomMapper;
    /**
     * 批量插入
     * */
    public void SimpleInsert(List<ScanPathVo> scanPathVos, Integer typeId, Short operType){
        if(null != scanPathVos && !scanPathVos.isEmpty()){
            Power_User user = (Power_User)((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute("CURRENT_USER");
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //查询表列数
            int colCount = commomMapper.selectColByTableName("emr_print_download_info");
            int simpleInsertCount = 2100/colCount;
            //定义批量添加下载记录
            List<EmrPrintDownloadInfo> list = new ArrayList<>();
            for (int i = 0; i < scanPathVos.size(); i++) {
                //处理批量添加sql太长问题，设定个数为180
                if(null != list && i > 0 && list.size()%simpleInsertCount == 0){
                    list.clear();
                }
                //添加下载记录对象
                EmrPrintDownloadInfo obj = new EmrPrintDownloadInfo();
                BeanUtils.copyProperties(scanPathVos.get(i),obj);
                obj.setTypeId(typeId);
                obj.setOperType(operType);
                obj.setCreater(user.getUserName());
                obj.setCreateTime(fmt.format(new Date()));
                obj.setIp(getOperIp());
                list.add(obj);
                //是180的倍数或最后一个
                if(null != list && (list.size()%simpleInsertCount == 0 || i == scanPathVos.size() - 1)) {
                    printDownloadInfoMapper.SimpleInsert(list);
                }
            }
        }
    }


    //获取操作人ip
    private String getOperIp(){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        // 获取访问真实IP
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }
    /**
     *按条件查询
     * */
    public List<EmrPrintOrDownLoadInfoVo> selectAll(EmrPrintOrDownLoadInfoVo emrPrintOrDownLoadInfoVo,String flag){
        List<EmrPrintOrDownLoadInfoVo> list = printDownloadInfoMapper.selectAll(emrPrintOrDownLoadInfoVo,flag);
        return getReturnList(list);
    }
    //组织数据
    private  List<EmrPrintOrDownLoadInfoVo> getReturnList(List<EmrPrintOrDownLoadInfoVo> list){
        List<EmrPrintOrDownLoadInfoVo> returnList = new ArrayList<>();
        if(null != list && !list.isEmpty()){
            Map<String,EmrPrintOrDownLoadInfoVo> map = new LinkedHashMap<>();
            for(EmrPrintOrDownLoadInfoVo vo : list){
                String key = vo.getPatientId() + "," + vo.getCreateTime() + "," + vo.getCreateTime();
                map.put(key,vo);
            }
            for(Map.Entry<String,EmrPrintOrDownLoadInfoVo> obj : map.entrySet()){
                String ids = "";
                String assortNames = "";
                String scanPages = "";
                int printCount = 0;
                Set<String> assortNameSet = new LinkedHashSet<>();
                for(EmrPrintOrDownLoadInfoVo vo : list){
                    String key = vo.getPatientId() + "," + vo.getCreateTime() + "," + vo.getCreateTime();
                    if(key.equals(obj.getKey())){
                        ids += vo.getId() + ",";
                        scanPages += vo.getScanPage() + ",";
                        assortNameSet.add(vo.getAssortName());
                        printCount++;
                    }
                }
                for(String assortName : assortNameSet){
                    assortNames += assortName + ",";
                }
                ids = ids.substring(0,ids.length() - 1);
                assortNames = assortNames.substring(0,assortNames.length() - 1);
                scanPages = scanPages.substring(0,scanPages.length() - 1);
                EmrPrintOrDownLoadInfoVo emrPrintOrDownLoadInfoVo = obj.getValue();
                emrPrintOrDownLoadInfoVo.setIds(ids);
                emrPrintOrDownLoadInfoVo.setAssortName(assortNames);
                emrPrintOrDownLoadInfoVo.setScanPage(scanPages);
                emrPrintOrDownLoadInfoVo.setPrintCount(printCount);
                returnList.add(emrPrintOrDownLoadInfoVo);
            }
        }
        return returnList;
    }
    /**
     *按复选框选中查询
     * */
    public List<EmrPrintOrDownLoadInfoVo> selectAllByIds(String ids,String flag){
        List<EmrPrintOrDownLoadInfoVo> list = printDownloadInfoMapper.selectAllByIds(ids,flag);
        return getReturnList(list);
    }

    /**
     *查询最近打印记录
     * */
    public List<EmrPrintOrDownLoadInfoVo> getPrintCount(String patientId){
        List<EmrPrintOrDownLoadInfoVo> list = printDownloadInfoMapper.getPrintCount(patientId);
        return list;
    }
}
