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

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.ResidentSignApplyMapper;
import com.xinelu.familydoctor.applet.pojo.body.ApprovalBody;
import com.xinelu.familydoctor.applet.pojo.body.MessagePushBody;
import com.xinelu.familydoctor.applet.pojo.body.ResidentSignApplyBody;
import com.xinelu.familydoctor.applet.pojo.dto.CrowdDto;
import com.xinelu.familydoctor.applet.pojo.dto.PackageDto;
import com.xinelu.familydoctor.applet.pojo.entity.PatientInfo;
import com.xinelu.familydoctor.applet.pojo.entity.ResidentSignApplyEntity;
import com.xinelu.familydoctor.applet.pojo.query.ApplyQuery;
import com.xinelu.familydoctor.applet.pojo.vo.ResidentSignApplyVo;
import com.xinelu.familydoctor.applet.pojo.vo.SignInfoDetailVo;
import com.xinelu.familydoctor.applet.service.IResidentPatientInfoService;
import com.xinelu.familydoctor.applet.service.IResidentSignAppletService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author mengkuiliang
 * @Description 签约申请Impl
 * @Date 2023-09-26 026 10:39
 * @Param
 * @return
 **/
@Service
public class ResidentSignApplyServiceImpl implements IResidentSignAppletService {

    @Resource
    private ResidentSignApplyMapper residentSignApplyMapper;
    @Resource
    private HttpService httpService;
    @Resource
    private IResidentPatientInfoService patientInfoService;
    @Resource
    private MessagePushService messagePushService;

    /**
     * 新增签约申请
     *
     * @param body :
     * @return Integer
     * @author lixinying
     * @date 2022/11/21 9:38
     */
    @Override
    public void insert(ResidentSignApplyBody body, String region) {
        ApplyQuery applyQuery = new ApplyQuery();
        applyQuery.setIdentity(body.getIdentity());
        applyQuery.setBookingStatus("0");
        applyQuery.setApprovalStatus("0");
        List<ResidentSignApplyVo> signBookingInfoVoList = residentSignApplyMapper.findByBody(applyQuery);
        if (signBookingInfoVoList != null && signBookingInfoVoList.size() > 0) {
            throw new ServiceException("已经提交签约申请，不能重复提交");
        }
        ResidentSignApplyEntity entity = new ResidentSignApplyEntity();
        BeanUtils.copyProperties(body, entity);

        PatientInfo patientInfo = patientInfoService.getByCardNo(body.getIdentity());
        if (patientInfo == null) {
            throw new ServiceException("未查询到注册信息");
        }
        if (StringUtils.isBlank(body.getPatientId())) {
            entity.setPatientId(patientInfo.getPatientCode());
        }

        entity.setApplyTime(new Date());
        // 预约状态0:已申请 1:已取消
        entity.setBookingStatus("0");
        // 审批状态0:待批准 1:已同意 2:已拒绝
        entity.setApprovalStatus("0");
        entity.setBookingNo(IdUtils.simpleUUID());
        if (StringUtils.isBlank(entity.getNation())) {
            entity.setNation("1");
        }
        if (entity.getSignYears() == null || entity.getSignYears() <= 0) {
            entity.setSignYears(1);
        }
        entity.setCrowdsNo(body.getCrowdList().stream().map(CrowdDto::getCrowdNo).collect(Collectors.joining(",")));
        entity.setCrowdsName(body.getCrowdList().stream().map(CrowdDto::getCrowdName).collect(Collectors.joining(",")));
        entity.setPackagesNo(body.getPackageList().stream().map(PackageDto::getPackageNo).collect(Collectors.joining(",")));
        entity.setPackagesName(body.getPackageList().stream().map(PackageDto::getPackageName).collect(Collectors.joining(",")));
        entity.setCityCode(region);
        residentSignApplyMapper.insert(entity);

        MessagePushBody messagePushBody = new MessagePushBody();
        messagePushBody.setMessageCategory("4");
        messagePushBody.setBusType("10");
        messagePushBody.setOpenid(patientInfo.getBindOpenid());
        messagePushBody.setReceiveName(body.getResidentName());
        messagePushBody.setText1(body.getOrgName());
        messagePushBody.setText2("签约申请");
        messagePushBody.setSendTitle("签约申请");
        messagePushBody.setSendTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", new Date()));
        messagePushBody.setSendContent(body.getResidentName() + "已提交申请");
        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<FdSignBookingVo>
     * @author lixinying
     * @date 2022/11/21 16:02
     */
    @Override
    public List<ResidentSignApplyVo> 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 residentSignApplyMapper.findByBody(query);
    }

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

    /**
     * @return com.xinelu.mp.sign.pojo.vo.FdSignBookingVo
     * @Author mengkuiliang
     * @Description 查询未完成的签约申请
     * @Date 2022-11-22 10:57
     * @Param [identity]
     **/
    @Override
    public ResidentSignApplyVo getSignBookingByIdentity(String identity, String region) {
        return residentSignApplyMapper.getSignBookingByIdentity(identity, region);
    }

    /**
     * @return com.xinelu.mp.sign.pojo.vo.FdSignBookingVo
     * @Author mengkuiliang
     * @Description 签约申请详情
     * @Date 2022-11-23 10:33
     * @Param [bookingNo]
     **/
    @Override
    public ResidentSignApplyVo detail(String bookingNo) {
        return residentSignApplyMapper.detail(bookingNo);
    }

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

    /**
     * @Author mengkuiliang
     * @Description 是否已申请签约
     * @Date 2022-11-30 9:49
     * @Param [identity]
     **/
    @Override
    public Map<String, Object> checkSignApply(String identity, String region) {
        Map<String, Object> retMap = new HashMap<>();
        // 查询未完成的签约申请
        ResidentSignApplyVo signBookingInfoVo = getSignBookingByIdentity(identity, region);
        if (signBookingInfoVo != null) {
            retMap.put("code", "01");
            retMap.put("info", DateUtils.parseDateToStr("yyyy年MM月dd日", signBookingInfoVo.getSignTime()) + "已在【" + signBookingInfoVo.getOrgName() + "】【" + signBookingInfoVo.getTeamName() + "】【" + signBookingInfoVo.getUserName() + "】申请签约");
            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;
        } else {
            retMap.put("code", "0");
            retMap.put("info", "未签约");
        }
        return retMap;
    }

}




