package com.emr.service.emrPrintOrDownLoadInfo;

import com.alibaba.fastjson.JSON;
import com.emr.dao.CommomMapper;
import com.emr.dao.Zd_AssortMapper;
import com.emr.dao.emrPrintAndDownLoad.EmrPrintDownloadInfoMapper;
import com.emr.entity.Power_User;
import com.emr.entity.Zd_Assort;
import com.emr.entity.emrPrintAndDownLoad.EmrPrintDownloadInfo;
import com.emr.service.CommomService;
import com.emr.vo.EmrPrintOrDownLoadInfo.EmrPrintOrDownLoadInfoVo;
import com.emr.vo.commomSearch.ScanPathVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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 {
    @Value("${printPrice}")
    private Float printPrice;
    @Autowired
    private EmrPrintDownloadInfoMapper printDownloadInfoMapper;
    @Autowired
    private Zd_AssortMapper assortMapper;
    @Autowired
    private CommomService commomService;
    /**
     * 批量插入
     * */
    public void SimpleInsert(List<ScanPathVo> scanPathVos, Integer typeId, Short operType){
        if(null != scanPathVos && !scanPathVos.isEmpty()){
            //定义不重复的主键集合
            Set<String> patientIdList = new HashSet<>();
            for (ScanPathVo scanPathVo : scanPathVos) {
                if(StringUtils.isNotBlank(scanPathVo.getPatientId())) {
                    patientIdList.add(scanPathVo.getPatientId());
                }
            }
            //组织批量插入集合
            List<EmrPrintDownloadInfo> batchInsertList = new ArrayList<>();
            //获取登录者用户名
            Power_User user = (Power_User)((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession().getAttribute("CURRENT_USER");
            //获取格式化日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //遍历主键组织批量插入集合
            for(String patientId : patientIdList){
                //定义不重复的分类id集合
                Set<String> assortList = new LinkedHashSet<>();
                for (ScanPathVo scanPathVo : scanPathVos) {
                    if(StringUtils.isNotBlank(scanPathVo.getAssortId()) && patientId.equals(scanPathVo.getPatientId())) {
                        assortList.add(scanPathVo.getAssortId());
                    }
                }
                //遍历组织Map
                //定义分类-图片Map
                Map<String,List<String>> map = new LinkedHashMap<>();
                //分patientId
                for(String assortId : assortList){
                    List<String> scanPageList = new ArrayList<>();
                    for (ScanPathVo scanPathVo : scanPathVos) {
                        //获取分类id
                        String assortIdTemp = scanPathVo.getAssortId();
                        //匹配图片分类
                        if(StringUtils.isNotBlank(assortIdTemp) && assortId.equals(assortIdTemp) && patientId.equals(scanPathVo.getPatientId())){
                            scanPageList.add(scanPathVo.getScanPage());
                        }
                    }
                    map.put(assortId,scanPageList);
                }
                //添加下载记录对象
                EmrPrintDownloadInfo obj = new EmrPrintDownloadInfo();
                obj.setTypeId(typeId);
                obj.setOperType(operType);
                obj.setCreater(user.getUserName());
                obj.setCreateTime(fmt.format(new Date()));
                obj.setIp(commomService.getOperIp());
                obj.setScanPage(JSON.toJSONString(map));
                obj.setPatientId(patientId);
                batchInsertList.add(obj);
            }
            //批量插入
            commomService.simpleInsert("emr_print_download_info",printDownloadInfoMapper,batchInsertList);
        }
    }


    //获取操作人ip

    /**
     *按条件查询
     * */
    public List<EmrPrintOrDownLoadInfoVo> selectAll(EmrPrintOrDownLoadInfoVo emrPrintOrDownLoadInfoVo){
        List<EmrPrintOrDownLoadInfoVo> list = printDownloadInfoMapper.selectAll(emrPrintOrDownLoadInfoVo);
        return getReturnList(list);
    }
    //组织数据
    private  List<EmrPrintOrDownLoadInfoVo> getReturnList(List<EmrPrintOrDownLoadInfoVo> list){
        if(null != list && !list.isEmpty()){
            //查询分类集合
            List<Zd_Assort> assortList = assortMapper.selectAll(new Zd_Assort());
            for(EmrPrintOrDownLoadInfoVo vo : list){
                //获取图片数据
                String scanPage = vo.getScanPage();
                //定义页数
                Integer printCount = 0;
                //json数据转对象
                Map<String,List> map = JSON.parseObject(scanPage, LinkedHashMap.class);
                if(!CollectionUtils.isEmpty(map)) {
                    //定义图片分类字符串
                    StringBuilder assortNames = new StringBuilder();
                    //定义图片名称字符串
                    StringBuilder scanPages = new StringBuilder();
                    //遍历map
                    for (Map.Entry<String, List> m : map.entrySet()) {
                        //获取图片分类
                        String assortId = m.getKey();
                        //转换分类名称
                        if (!CollectionUtils.isEmpty(assortList)) {
                            for (Zd_Assort assort : assortList) {
                                if (StringUtils.isNotBlank(assort.getAssortId()) &&
                                        assortId.equals(assort.getAssortId())) {
                                    if (StringUtils.isNotBlank(assort.getAssortName())) {
                                        assortNames.append(assort.getAssortName()).append(",");
                                    }
                                    break;
                                }
                            }
                        }
                        //获取图片名称
                        List<String> scanPageList = m.getValue();
                        //遍历图片名称
                        for (String scanPageTemp : scanPageList) {
                            scanPages.append(scanPageTemp).append(",");
                            printCount++;
                        }
                    }
                    //去掉尾部逗号
                    if (StringUtils.isNotBlank(assortNames)) {
                        assortNames = new StringBuilder(assortNames.substring(0, assortNames.length() - 1));
                        vo.setAssortName(assortNames.toString());
                    }
                    //去掉尾部逗号
                    if (StringUtils.isNotBlank(scanPages)) {
                        scanPages = new StringBuilder(scanPages.substring(0, scanPages.length() - 1));
                        vo.setScanPage(scanPages.toString());
                    }
                }else{
                    vo.setAssortName(null);
                    vo.setScanPage(null);
                }
                vo.setPrintCount(printCount);
                vo.setPrintFee(printCount * printPrice);
                if (vo.getTypeName().equals("院内查阅")){
                    vo.setPrintFee(0 * printPrice);
                }
                if (vo.getTypeName().equals("公检法单位")){
                    vo.setPrintFee(0 * printPrice);
                }
            }
        }
        return list;
    }
    /**
     *按复选框选中查询
     * */
    public List<EmrPrintOrDownLoadInfoVo> selectAllByIds(String ids,String flag){
        List<EmrPrintOrDownLoadInfoVo> list = printDownloadInfoMapper.selectAllByIds(ids,flag);
        return getReturnList(list);
    }

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