package com.xinelu.familydoctor.applet.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.xinelu.manage.service.messagepush.MessagePushService;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.DateUtils;
import com.xinelu.common.utils.StringUtils;
import com.xinelu.common.utils.http.HttpService;
import com.xinelu.common.utils.spring.SpringUtils;
import com.xinelu.common.utils.uuid.IdUtils;
import com.xinelu.familydoctor.applet.mapper.ResidentServiceApplyMapper;
import com.xinelu.familydoctor.applet.pojo.body.ApprovalBody;
import com.xinelu.familydoctor.applet.pojo.body.MessagePushBody;
import com.xinelu.familydoctor.applet.pojo.body.ResidentServiceApplyBody;
import com.xinelu.familydoctor.applet.pojo.entity.PatientInfo;
import com.xinelu.familydoctor.applet.pojo.entity.ResidentServiceApplyEntity;
import com.xinelu.familydoctor.applet.pojo.query.ApplyQuery;
import com.xinelu.familydoctor.applet.pojo.vo.*;
import com.xinelu.familydoctor.applet.service.IResidentPatientInfoService;
import com.xinelu.familydoctor.applet.service.IResidentServiceAppletService;
import com.xinelu.manage.domain.hospitalinfo.HospitalInfo;
import com.xinelu.manage.domain.screeningproject.ScreeningProject;
import com.xinelu.manage.service.hospitalinfo.IHospitalInfoService;
import com.xinelu.manage.service.screeningproject.IScreeningProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author mengkuiliang
 * @Description 服务申请Impl
 * @Date 2023-10-07 007 11:38
 * @Param
 * @return
 **/
@Service
public class ResidentServiceApplyServiceImpl implements IResidentServiceAppletService {

    @Resource
    private ResidentServiceApplyMapper residentServiceApplyMapper;
    @Resource
    private HttpService httpService;
    @Resource
    private IResidentPatientInfoService patientInfoService;
    @Resource
    private IHospitalInfoService hospitalInfoService;
    @Resource
    private IScreeningProjectService screeningProjectService;
    @Resource
    private MessagePushService messagePushService;

    /**
     * 新增服务申请
     *
     * @param body :
     * @return Integer
     * @author lixinying
     * @date 2022/11/21 9:38
     */
    @Override
    public void insert(ResidentServiceApplyBody body) {
        ApplyQuery applyQuery = new ApplyQuery();
        applyQuery.setIdentity(body.getIdentity());
        applyQuery.setBookingStatus("0");
        applyQuery.setApprovalStatus("0");
        applyQuery.setFormNo(body.getFormNo());
        List<ResidentServiceApplyVo> serviceBookingInfoVoList = residentServiceApplyMapper.findByBody(applyQuery);
        if (serviceBookingInfoVoList != null && serviceBookingInfoVoList.size() > 0) {
            throw new ServiceException("已提交该服务申请，不能重复提交");
        }
        ResidentServiceApplyEntity entity;
        PatientInfo patientInfo = patientInfoService.getByCardNo(body.getIdentity());
        if (patientInfo == null) {
            throw new ServiceException("未查询到注册信息");
        }

        entity = new ResidentServiceApplyEntity();
        BeanUtils.copyProperties(body, entity);
        if (StringUtils.isBlank(entity.getPatientId())) {
            entity.setPatientId(patientInfo.getPatientCode());
        }
        entity.setApplyTime(new Date());
        // 预约状态0：已申请1：已完成2：已取消
        entity.setBookingStatus("0");
        // 审批状态0:待批准 1:已同意 2:已拒绝
        entity.setApprovalStatus("0");
        entity.setBookingNo(IdUtils.simpleUUID());
        entity.setOrgNo(body.getHospitalId());
        entity.setOrgName(body.getHospitalName());
        if(StringUtils.isBlank(entity.getServiceWay())) {
            entity.setServiceWay("2");
        }
        if(StringUtils.isBlank(entity.getResidentName())) {
            entity.setResidentName(patientInfo.getPatientName());
        }
        residentServiceApplyMapper.insert(entity);

        MessagePushBody messagePushBody = new MessagePushBody();
        messagePushBody.setMessageCategory("4");
        messagePushBody.setBusType("10");
        messagePushBody.setOpenid(patientInfo.getBindOpenid());
        messagePushBody.setReceiveName(patientInfo.getPatientName());
        messagePushBody.setText1(body.getHospitalName());
        messagePushBody.setText2(body.getFormName().length() >= 20? body.getFormName().substring(0,17) + "...": body.getFormName());
        messagePushBody.setText3(body.getFormName());
        messagePushBody.setSendTitle("服务预约");
        messagePushBody.setSendTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        messagePushBody.setSendContent(patientInfo.getPatientName() + "已提交服务申请");
        messagePushBody.setCardNo(body.getIdentity());
        messagePushService.fdApprovePush(JSONObject.parseObject(JSONObject.toJSONString(messagePushBody)));
    }

    /**
     * 取消
     *
     * @param bookingNo :
     * @return Integer
     * @author lixinying
     * @date 2022/11/21 10:10
     */
    @Override
    public Integer delete(String bookingNo) {
        return null;
    }

    /**
     * fd查找
     *
     * @param query :
     * @return List<FdServiceBookingVo>
     * @author lixinying
     * @date 2022/11/21 16:02
     */
    @Override
    public List<ResidentServiceApplyVo> findList(ApplyQuery query) {
        if (query.getStartDate() != null) {
            query.setStartDate(DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", query.getStartDate())));
        }
        if (query.getEndDate() != null) {
            query.setEndDate(DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", query.getEndDate())));
        }
        return residentServiceApplyMapper.findByBody(query);
    }

    /**
     * 修改审批
     *
     * @param body :
     * @return Integer
     * @author lixinying
     * @date 2022/11/21 17:07
     */
    @Override
    public Integer updateFd(ApprovalBody body) {
        return residentServiceApplyMapper.updateEx(body);
    }

    /**
     * @return com.xinelu.mp.sign.pojo.vo.FdServiceBookingVo
     * @Author mengkuiliang
     * @Description 查询未完成的服务申请
     * @Date 2022-11-22 10:57
     * @Param [identity]
     **/
    @Override
    public ResidentServiceApplyVo getServiceBookingByIdentity(String identity) {
        return residentServiceApplyMapper.getServiceBookingByIdentity(identity);
    }

    /**
     * @return com.xinelu.mp.sign.pojo.vo.FdServiceBookingVo
     * @Author mengkuiliang
     * @Description 服务申请详情
     * @Date 2022-11-23 10:33
     * @Param [bookingNo]
     **/
    @Override
    public ResidentServiceApplyVo detail(String bookingNo) {
        return residentServiceApplyMapper.detail(bookingNo);
    }

    /**
     * @return void
     * @Author mengkuiliang
     * @Description 取消服务申请
     * @Date 2022-11-23 14:42
     * @Param [bookingNo]
     **/
    @Override
    public void cancel(String bookingNo) {
        ResidentServiceApplyVo residentServiceApplyVo = residentServiceApplyMapper.detail(bookingNo);
        if (residentServiceApplyVo == null) {
            throw new ServiceException("未查询到申请记录");
        }
        if (!StringUtils.isBlank(residentServiceApplyVo.getBookingStatus())) {
            if (residentServiceApplyVo.getBookingStatus().equals("1")) {
                throw new ServiceException("已完成，不能取消");
            } else if (residentServiceApplyVo.getBookingStatus().equals("2")) {
                throw new ServiceException("不能重复取消");
            }
        }
        if (!StringUtils.isBlank(residentServiceApplyVo.getApprovalStatus())) {
            if (residentServiceApplyVo.getApprovalStatus().equals("1")) {
                throw new ServiceException("已同意，不能取消");
            }
            if (residentServiceApplyVo.getApprovalStatus().equals("2")) {
                throw new ServiceException("已拒绝，不能取消");
            }
        }
        residentServiceApplyMapper.cancel(bookingNo);
    }

    /**
     * @Author mengkuiliang
     * @Description 是否已申请服务
     * @Date 2022-11-30 9:49
     * @Param [identity]
     **/
    @Override
    public Map<String, Object> checkServiceApply(String identity, String region) {
        Map<String, Object> retMap = new HashMap<>();
        // 查询未完成的服务申请
        ResidentServiceApplyVo serviceBookingInfoVo = getServiceBookingByIdentity(identity);
        if (serviceBookingInfoVo != null) {
            retMap.put("code", 01);
            retMap.put("info", DateUtils.parseDateToStr("yyyy年MM月dd日", serviceBookingInfoVo.getBookingTime()) + "已申请" + serviceBookingInfoVo.getFormName() + "服务");
            return retMap;
        }
        // 查询服务信息
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/detail/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            throw new ServiceException(jsonObject.get("msg").toString());
        }
        // 已服务
        if (jsonObject.containsKey("data") && jsonObject.get("data") != null) {
            SignInfoDetailVo signInfoDetailVo = JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), SignInfoDetailVo.class);
            retMap.put("code", 02);
            retMap.put("info", DateUtils.parseDateToStr("yyyy年MM月dd日", signInfoDetailVo.getSignTime()) + "已在【" + signInfoDetailVo.getOrgName() + "】【" + signInfoDetailVo.getTeamName() + "】【" + signInfoDetailVo.getUserName() + "】服务");
            return retMap;
        }
        retMap.put("code", 0);
        retMap.put("info", "true");
        return retMap;
    }

    /**
     * @return void
     * @Author mengkuiliang
     * @Description 更新服务完成时间
     * @Date 2022-11-29 14:21
     * @Param [body]
     **/
    @Override
    public void updateComplete(String bookingNo) {
        residentServiceApplyMapper.updateComplete(bookingNo);
    }

    /**
     * @return java.util.List<?>
     * @Author mengkuiliang
     * @Description 获取个性服务包和筛查项目
     * @Date 2023-10-09 009 10:55
     * @Param [identity]
     **/
    @Override
    public List<ScreeningProjectVo> getForm(String identity, String projectName, String region) {
        List<ScreeningProjectVo> projectList = new ArrayList<>();
        // 获取签约信息
        String result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/resident/signinfo/detail/" + identity, null, String.class);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            throw new ServiceException(jsonObject.get("msg").toString());
        }
        if (!jsonObject.containsKey("data") || jsonObject.get("data") == null) {
            throw new ServiceException("未查询到签约信息");
        }
        SignInfoDetailVo signInfo = JSONObject.parseObject(jsonObject.getJSONObject("data").toJSONString(), SignInfoDetailVo.class);
        if (signInfo == null) {
            throw new ServiceException("未查询到签约信息!");
        }
        // 1、获取家医个性服务包
        result = (String) httpService.get(SpringUtils.getFdUrl(region) + "/package/getPackageOfGX/" + identity + (!StringUtils.isBlank(projectName) ? ("?formName=" + projectName) : "?formName=null"), null, String.class);
        jsonObject = JSONObject.parseObject(result);
        if (!"1".equals(jsonObject.get("code"))) {
            throw new ServiceException(jsonObject.get("msg").toString());
        }
        if (jsonObject.containsKey("data") && jsonObject.get("data") != null) {
            List<PerformanceDetailVo> perList = JSONArray.parseArray(jsonObject.getJSONArray("data").toJSONString()).toJavaList(PerformanceDetailVo.class);
            if (perList.size() > 0) {
                ScreeningProjectVo sp;
                for (PerformanceDetailVo per : perList) {
                    sp = new ScreeningProjectVo();
                    sp.setSourceType("1");
                    sp.setHospitalId(per.getOrgNo());
                    sp.setHospitalName(per.getOrgName());
                    sp.setPackageId(per.getPackageNo());
                    sp.setPackageName(per.getPackageName());
                    sp.setProjectId(per.getFormNo());
                    sp.setProjectName(per.getFormName());
                    sp.setPrice(per.getPackCost());
                    sp.setDiscountPrice(per.getPackSignCost());
                    sp.setServiceFreq(per.getServiceFreq());
                    sp.setPerformanceCount(per.getPerformanceCount());
                    sp.setTeamNo(per.getTeamNo());
                    sp.setTeamName(per.getTeamName());
                    sp.setUserNo(per.getUserNo());
                    sp.setUserName(per.getUserName());
                    projectList.add(sp);
                }
            }
        }

        // 2、获取签约机构下的筛查项目
        // 根据机构编码获取筛查机构
        HospitalInfo Hospital = hospitalInfoService.getHosptalByOrgCode(signInfo.getOrgNo());
        if (Hospital != null) {
            // 获取筛查项目
            ScreeningProject query = new ScreeningProject();
            query.setHospitalId(Hospital.getId());
            query.setProjectName(projectName);
            List<ScreeningProject> screeningProjectList = screeningProjectService.findList(query);
            if (screeningProjectList != null && screeningProjectList.size() > 0) {
                ScreeningProjectVo sp;
                for (ScreeningProject project : screeningProjectList) {
                    sp = new ScreeningProjectVo();
                    sp.setSourceType("2");
                    sp.setHospitalId(String.valueOf(project.getHospitalId()));
                    sp.setHospitalName(project.getHospitalName());
                    sp.setProjectId(project.getProjectId());
                    sp.setProjectName(project.getProjectName());
                    sp.setPrice(project.getPrice());
                    sp.setDiscountPrice(project.getDiscountPrice());
                    sp.setPackageName(project.getHospitalName());
                    projectList.add(sp);
                }
            }
        }

        return projectList;
    }

    /**
     * @Author mengkuiliang
     * @Description 服务记录列表
     * @Date 2023-10-13 013 13:56
     * @Param [query]
     * @return java.util.List<com.xinelu.familydoctor.applet.pojo.vo.ResidentServiceApplyVo>
     **/
    @Override
    public List<ResidentServiceApplyVo> record(ApplyQuery query) {
        if (query.getStartDate() != null) {
            query.setStartDate(DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd 00:00:00", query.getStartDate())));
        }
        if (query.getEndDate() != null) {
            query.setEndDate(DateUtils.parseDate(DateUtils.parseDateToStr("yyyy-MM-dd 23:59:59", query.getEndDate())));
        }
        return residentServiceApplyMapper.getRecord(query);
    }
}




