package thyyxxk.webserver.service.bodyexam;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.bodyexam.BodyExamDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.service.externalhttp.PowersiTjReport;
import thyyxxk.webserver.utils.ResultVoUtil;
import thyyxxk.webserver.utils.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName BodyExamService
 * @Description 体检数据获取
 * @Author hsh
 * @Date 2022/8/15 16:43
 **/
@Service
public class BodyExamService {

    private final PowersiTjReport report;

    private final BodyExamDao dao;

    @Autowired
    public BodyExamService(PowersiTjReport report, BodyExamDao dao) {
        this.report = report;
        this.dao = dao;
    }

    public ResultVo<List<Map>> getTjReportData(Map<String, String> map){
        String id = map.get("tjid");
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "参数id为空");
        }

        id = dao.getTjIdByCode(id);
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检信息为空, 查询失败");
        }

        // 个人信息
        JSONObject result1 = report.getTjReportPersonalInfo(id);
        // 体检结果
        JSONObject result2 = report.getTjReportResult(id);
        // 体检汇总信息
        JSONObject result3 = report.getTjReportTotalInfo(id);
        // 体检模块信息
        JSONObject result4 = report.getTjReportModuleInfo(id);

        List<Map> list = new ArrayList<>();
        JSONArray rows1 = result1.getJSONArray("rows");
        if(rows1 != null && rows1.size()> 0){
            List<Map> list1 = rows1.toJavaList(Map.class);
            Map p = new HashMap<>();
            p.put("reportHeader", list1.get(0));
            list.add(p);
        }

        // 体检结果和体检模块信息需要汇总在一块
        // 顺便提取所有的检验项目或者检查科室
        List<Map> item = new ArrayList<>();
        JSONArray rows2 = result2.getJSONArray("rows");
        if(rows2 != null && rows2.size() > 0){
            List<Map> list2 = rows2.toJavaList(Map.class);
            Map<String, List<Map>> m = list2.stream().collect(Collectors.groupingBy(f -> String.valueOf(f.get("检查单元C")), Collectors.toList()));
            for(Map.Entry<String, List<Map>> entry : m.entrySet()){
                Map<String, List<Map>> reMap = new HashMap<>();
                String key = entry.getKey();
                List<Map> l = entry.getValue();
                JSONArray rows4 = result4.getJSONArray("rows");
                if(rows4 != null && rows4.size() > 0){
                    List<Map> list4 = rows4.toJavaList(Map.class);
                    for(Map m4 : list4){
                        String d = m4.get("体检单元名称") + "";
                        String sj = m4.get("检查日期") + "";
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String dateString = "";
                        if(!"null".equals(sj)){
                            long times = Long.parseLong(sj);
                            Date date = new Date(times);
                            dateString =  formatter.format(date);
                        }
                        if(key.equals(d)){
                            Map map1 = new HashMap();
                            map1.put("time", dateString);
                            map1.put("name", d);
                            item.add(map1);
                            l.add(m4);
                            break;
                        }
                    }
                }
                reMap.put(key, l);
                list.add(reMap);
            }
        }

        if(item != null && item.size() > 0){
            Map p1 = new HashMap<>();
            List<Map> listItem = item.stream().sorted(Comparator.comparing(a -> String.valueOf(a.get("time")))).collect(Collectors.toList());
            p1.put("reportItems", listItem);
            list.add(p1);
        }

        JSONArray rows3 = result3.getJSONArray("rows");
        if(rows3 != null && rows3.size() > 0){
            List<Map> list3 = rows3.toJavaList(Map.class);
            String sumStr = String.valueOf(list3.get(0).get("汇总建议"));
            sumStr = sumStr.replace("\r\n\r\n", "<br /><br />").replace("\r\n", "<br />");
            list3.get(0).put("汇总建议", sumStr);
            Map p3 = new HashMap<>();
            p3.put("reportSummary", list3.get(0));
            list.add(p3);
        }

        return ResultVoUtil.success(list);
    }

    /**
     *@Author hsh
     *@Description // 获取体检个人信息
     *@Date 2022/8/15 17:08
     *@Param [map]
     *@Return thyyxxk.webserver.entity.ResultVo<java.util.List<java.util.Map>>
     **/
    public ResultVo<List<Map>> getTjReportPersonalInfo(Map<String, String> map){
        String id = map.get("tjid");
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检id为空");
        }
        JSONObject result = report.getTjReportPersonalInfo(id);

        if(result == null || result.isEmpty()){
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有体检数据");
        }

        JSONArray rows = result.getJSONArray("rows");
        List<Map> list = rows.toJavaList(Map.class);

        return ResultVoUtil.success(list);
    }

    /**
     *@Author hsh
     *@Description // 体检汇总信息
     *@Date 2022/8/15 17:29
     *@Param [map]
     *@Return thyyxxk.webserver.entity.ResultVo<java.util.List<java.util.Map>>
     **/
    public ResultVo<List<Map>> getTjReportTotalInfo(Map<String, String> map){
        String id = map.get("tjid");
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检id为空");
        }
        JSONObject result = report.getTjReportTotalInfo(id);

        if(result == null || result.isEmpty()){
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有体检数据");
        }

        JSONArray rows = result.getJSONArray("rows");
        List<Map> list = rows.toJavaList(Map.class);

        return ResultVoUtil.success(list);
    }

    /**
     *@Author hsh
     *@Description // 体检结果
     *@Date 2022/8/16 8:54
     *@Param [map]
     *@Return thyyxxk.webserver.entity.ResultVo<java.util.List<java.util.Map>>
     **/
    public ResultVo<List<Map>> getTjReportResult(Map<String, String> map){
        String id = map.get("tjid");
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检id为空");
        }
        JSONObject result = report.getTjReportResult(id);

        if(result == null || result.isEmpty()){
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有体检数据");
        }

        JSONArray rows = result.getJSONArray("rows");
        List<Map> list = rows.toJavaList(Map.class);

        return ResultVoUtil.success(list);
    }

    /**
     *@Author hsh
     *@Description // 体检模块信息
     *@Date 2022/8/16 8:55
     *@Param [map]
     *@Return thyyxxk.webserver.entity.ResultVo<java.util.List<java.util.Map>>
     **/
    public ResultVo<List<Map>> getTjReportModuleInfo(Map<String, String> map){
        String id = map.get("tjid");
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检id为空");
        }
        JSONObject result = report.getTjReportModuleInfo(id);

        if(result == null || result.isEmpty()){
            return ResultVoUtil.fail(ExceptionEnum.NO_DATA_EXIST, "没有体检数据");
        }

        JSONArray rows = result.getJSONArray("rows");
        List<Map> list = rows.toJavaList(Map.class);

        return ResultVoUtil.success(list);
    }

    /**
     * @Description 体检信息
     * @Author hsh
     * @param tjId 体检号
     * @return Map
     * @Date 2023/12/9 16:05
     */
    public ResultVo<Map> selectTjReportInfoById(String tjId){

        if(StringUtil.isBlank(tjId)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "参数为空，查询失败");
        }

        String id = dao.getTjIdByCode(tjId);
        if(StringUtil.isBlank(id)){
            return ResultVoUtil.fail(ExceptionEnum.INVALID_PARAM, "体检信息为空, 查询失败");
        }

        Map m = new HashMap<>();
        // 个人信息
        JSONObject result1 = report.getTjReportPersonalInfo(id);
        m.put("personalInfo", result1);
        // 体检结果
        JSONObject result2 = report.getTjReportResult(id);
        m.put("result", result1);
        // 体检汇总信息
        JSONObject result3 = report.getTjReportTotalInfo(id);
        m.put("totalInfo", result1);
        // 体检模块信息
        JSONObject result4 = report.getTjReportModuleInfo(id);
        m.put("moduleInfo", result1);
        return ResultVoUtil.success(m);
    }

}
