package thyyxxk.webserver.service.mz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.exception.ExceptionEnum;
import thyyxxk.webserver.dao.his.mz.MzEmrDao;
import thyyxxk.webserver.dao.his.zhuyuanyisheng.emr.EmrPatientDao;
import thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.entity.login.UserInfo;
import thyyxxk.webserver.entity.mz.MzEmrPatientData;
import thyyxxk.webserver.entity.mz.MzEmrPatientVo;
import thyyxxk.webserver.service.externalhttp.emr.EmrEditor;
import thyyxxk.webserver.service.redislike.RedisLikeService;
import thyyxxk.webserver.utils.AssertUtil;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author:lihong
 * @Date: 2023/10/18
 */
@Service
public class MzEmrService {
    @Autowired
    private MzEmrDao dao;
    @Autowired
    private EmrEditor emr;
    @Autowired
    private EmrPatientDao emrPatientDao;
    @Autowired
    private RedisLikeService redisLikeService;


    public JSONArray getMzEmrModel() {
        return emr.getDeptList("1400000");
    }

    /**
     * @description:查询 1住院 2当前  3历史记录
     * @author: lihong
     * @date: 2023/10/18 16:51
     * @param: type
     * @return: java.util.Map<java.lang.String,java.util.List<com.alibaba.fastjson.JSONObject>>
     **/
    public List<MzEmrPatientData> queryMzEmrTree(MzEmrPatientVo param) {
        List<MzEmrPatientData> result = new ArrayList();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("pat_no", param.getPatientId());
        String strTemplate = "";
        List<MzEmrPatientData> list;
        if (param.getType() == 1) {
            String patNo = dao.selectPatNo(param.getPatientId());
            list = emrPatientDao.selectDataByPatNo(patNo);
            strTemplate = "第{}住院记录";
        } else if (param.getType() == 2) {
            queryWrapper.eq("times", param.getTimes());
            list = dao.selectList(queryWrapper);
            return list;
        } else {
            strTemplate = "第{}就诊记录";
            queryWrapper.ne("times", param.getTimes());
            list = dao.selectList(queryWrapper);
        }
        result = getTree(list, strTemplate);
        return result;
    }


    private   List<MzEmrPatientData> getTree(List<MzEmrPatientData> list,String strTemplate) {
        if(CollUtil.isEmpty(list)) return list;
        List<MzEmrPatientData> result = new ArrayList<>();
        Map<Integer, List<MzEmrPatientData>> collect = list.stream().collect(Collectors.groupingBy(o -> o.getTimes()));
        int index = 1;
        for(Integer key :collect.keySet()){
            MzEmrPatientData tem = new MzEmrPatientData();
            tem.setId(index);
            tem.setName(StrUtil.format(strTemplate,key));
            tem.setChildren(collect.get(key));
            result.add(tem);
        }
        return result;
    }

    public MzEmrPatientVo queryMzPatientInfo(MzEmrPatientVo param) {
        AssertUtil.isnotBlank(param.getPatientId(),"门诊号不能为空");
        MzEmrPatientVo data = dao.selectMzEmrPatientVo(param);
       if(StrUtil.isNotBlank(param.getUserIdCode())){
           UserInfo userInfo = redisLikeService.getUserInfoByCode(param.getUserIdCode());
           data.setUserName(redisLikeService.getEmployeeName(param.getUserIdCode()));
           data.setDeptCode(userInfo.getDeptCode());
           data.setDeptName(redisLikeService.getDeptName(userInfo.getDeptCode()));
       }
        if (data.getAge() == null) {
            if (data.getBirthDay() != null) {
                data.setAge(DateUtil.age(data.getBirthDay(), null));
            } else {
                data.setAge(DateUtil.age(IdcardUtil.getBirthDate(data.getSocialNo()),null));
            }
        }
        data.setPatientId(param.getPatientId());
        data.setTimes(param.getTimes());
        data.setUserIdCode(param.getUserIdCode());
        BeanUtil.trimStrFields(data);
        return data;
    }


    public ResultVo<String> saveMzEmrModel(MzEmrPatientData param) {
        AssertUtil.isnotBlank(param.getEmrDocumentId(),"文档id不能为空");
        AssertUtil.isnotBlank(param.getUserIdCode(),"用户不能为空");
        JSONObject saveJson = new JSONObject();
        saveJson.put("document", param.getDocumentData());
        try {
            emr.saveDocument(saveJson);
        } catch (Exception e) {
            return ResultVoUtil.fail(ExceptionEnum.EMR_SAVE, "病历保存错误，请重试！" + e.getMessage());
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("emr_document_id", param.getEmrDocumentId());
        MzEmrPatientData mzEmrPatientData = dao.selectOne(queryWrapper);
        if (mzEmrPatientData == null) {
            param.setCreateId(param.getUserIdCode());
            dao.insert(param);
        } else {
            param.setModifyId(param.getUserIdCode());
            param.setModifyDate(new Date());
            UpdateWrapper updateWrapper = new UpdateWrapper();
            updateWrapper.eq("emr_document_id", param.getEmrDocumentId());
            dao.update(param,updateWrapper);
        }
        return ResultVoUtil.success(ExceptionEnum.SUCCESS_AND_EL_MESSAGE,"保存成功");
    }
}
