package com.fs.hisStore.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.his.domain.*;
import com.fs.his.dto.*;
import com.fs.his.mapper.*;
import com.fs.his.service.IFsQuestionAndAnswerService;
import com.fs.his.service.IPollingAssignDoctorService;
import com.fs.his.utils.IdCardUtil;
import com.fs.his.vo.*;
import com.fs.hisStore.domain.FsUserInformationCollection;
import com.fs.hisStore.mapper.FsUserInformationCollectionMapper;
import com.fs.hisStore.service.IOpenApiCPWUserInformationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 对接-超拼网-信息采集服务实现类
 * */
@Slf4j
@Service
public class OpenApiCPWUserInformationServiceImpl implements IOpenApiCPWUserInformationService {

    /** 默认患者问题模板id */
    private static final Long QUESTION_ID = 10L;

    @Autowired
    private IFsQuestionAndAnswerService questionAndAnswerService;

    @Autowired
    private FsUserMapper fsUserMapper;

    @Autowired
    private FsUserAddressMapper fsUserAddressMapper;

    @Autowired
    private FsUserInformationCollectionMapper fsUserInformationCollectionMapper;

    @Autowired
    private FsPrescribeMapper prescribeMapper;

    @Autowired
    private FsPrescribeDrugMapper prescribeDrugMapper;

    @Autowired
    private FsDoctorMapper doctorMapper;

    @Autowired
    private IPollingAssignDoctorService pollingAssignDoctorService;

    @Override
    public FsQuestionAndAnswerVO getInformationTemplate() {
        try {
            FsQuestionAndAnswerVO questionAndAnswerVo = questionAndAnswerService.selectFsQuestionAndAnswerById(QUESTION_ID);
            if (questionAndAnswerVo == null) {
                log.error("未找到患者问题模板,模板id:{}", QUESTION_ID);
                throw new CustomException("未找到信息采集模板", 404);
            }
            return questionAndAnswerVo;
        } catch (Exception e) {
            log.error("获取信息采集模板失败", e);
            throw new CustomException("获取信息采集模板失败，请稍后重试", 500);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmitUserInformationVO submitPatientPrescriptionInfo(CPWUserInfoCollectionAddDTO collectionAddDTO) {
        Long patientId = collectionAddDTO.getPatientInfo().getPatientId();
        //查询此用户最新的开方进度是否已完成，已完成才能新增待开处方
        FsPrescribeListVO fsPrescribeListVO = prescribeMapper.selectFsPrescribeListVOByThirdUserId(patientId);
        if (fsPrescribeListVO!=null){
            if (fsPrescribeListVO.getStatus() == 0 && StringUtils.isBlank(fsPrescribeListVO.getPrescribeImgUrl())) {
                log.error("超拼网用户[{}]重复提交待开处方，当前状态：待医生开方", patientId);
                throw new CustomException("您已提交待开方申请，请等待医生开方处理，请勿重复提交", 400);
            } else if (fsPrescribeListVO.getStatus() == 0 && StringUtils.isNotBlank(fsPrescribeListVO.getPrescribeImgUrl())) {
                log.error("超拼网用户[{}]处方处于待审核状态，处方ID：{}", patientId, fsPrescribeListVO.getPrescribeId());
                throw new CustomException("您的处方正在审核中，请耐心等待药师审核结果", 400);
            } else if (fsPrescribeListVO.getStatus() == 2) {
                log.error("超拼网用户[{}]处方药师审核未通过，处方ID：{}", patientId, fsPrescribeListVO.getPrescribeId());
                throw new CustomException("您的处方药师审核未通过，待医生重新开方中", 400);
            }
        }
        //新增fs_user_information_collection用户信息采集信息
        FsUserInformationCollection queryFsUserInformationCollection=new FsUserInformationCollection();
        queryFsUserInformationCollection.setThirdPartyUserId(patientId);
        queryFsUserInformationCollection.setInfoSource(2);//采集信息来源：超拼网用户
        FsUserInformationCollection fsUserInformationCollection = transformCollectionDtoToFsUserCollection(collectionAddDTO);
        List<FsUserInformationCollection> fsUserInformationCollections = fsUserInformationCollectionMapper.selectFsUserInformationCollectionList(queryFsUserInformationCollection);
        if (CollectionUtils.isEmpty(fsUserInformationCollections)){
            int addInfoResult = fsUserInformationCollectionMapper.insertFsUserInformationCollection(fsUserInformationCollection);
            if (addInfoResult <= 0) {
                throw new CustomException("患者采集信息保存失败", 500);
            }
        }else {
            //存在则更新
            fsUserInformationCollection.setId(fsUserInformationCollections.get(0).getId());
            fsUserInformationCollectionMapper.updateFsUserInformationCollection(fsUserInformationCollection);
        }
        //新增fs_prescribe处方信息
        FsPrescribe fsPrescribe= transformCollectionDtoToFsPrescribe(collectionAddDTO,fsUserInformationCollection);
        int addPrescribeResult = prescribeMapper.insertFsPrescribe(fsPrescribe);
        if (addPrescribeResult <= 0) {
            throw new CustomException("患者处方信息保存失败", 500);
        }
        //构建成功返回结果
        SubmitUserInformationVO resultVO = new SubmitUserInformationVO();
        resultVO.setPatientId(fsUserInformationCollection.getThirdPartyUserId());
        resultVO.setCollectionId(fsUserInformationCollection.getId());
        resultVO.setStatus(BigDecimal.ONE.intValue());
        resultVO.setMessage("提交成功");
        resultVO.setSubmitTime(DateUtils.getTime());
        log.info("超拼网---用户待开方信息提交成功，patientName: {}, collectionId: {}",
                collectionAddDTO.getPatientInfo().getPatientName(), fsUserInformationCollection.getId());
        return resultVO;
    }

    private FsPrescribe transformCollectionDtoToFsPrescribe(CPWUserInfoCollectionAddDTO collectionAddDTO,FsUserInformationCollection fsUserInformationCollection) {
        CPWPatientInfoAddDTO patientInfo = collectionAddDTO.getPatientInfo();
        FsPrescribe fsPrescribe=new FsPrescribe();
        fsPrescribe.setThirdPartyUserId(collectionAddDTO.getPatientInfo().getPatientId());
        fsPrescribe.setCreateTime(DateUtils.getNowDate());
        fsPrescribe.setStatus(0);//待开方
        fsPrescribe.setDoctorConfirm(0);//未确认
        //fsPrescribe.setUsageJson(JSON.toJSONString(collectionAddDTO.getAnswers()));
        fsPrescribe.setHistoryAllergic(collectionAddDTO.getAllergy());
        String prescribeCode= IdUtil.getSnowflake(0, 0).nextIdStr();
        fsPrescribe.setPrescribeCode(prescribeCode);
        fsPrescribe.setPatientAge(String.valueOf(fsUserInformationCollection.getAge()));
        fsPrescribe.setPatientId(patientInfo.getPatientId());
        fsPrescribe.setPatientName(patientInfo.getPatientName());
        fsPrescribe.setPatientTel(patientInfo.getPatientTel());
        fsPrescribe.setPatientGender(patientInfo.getPatientGender());
        fsPrescribe.setPatientBirthday(patientInfo.getPatientBirthday());
        fsPrescribe.setWeight(patientInfo.getWeight());
        Long doctorId = 437L;
        fsPrescribe.setDoctorId(doctorId);
        FsDoctor fsDoctor = doctorMapper.selectFsDoctorByDoctorId(doctorId);
        if (fsDoctor==null){
            throw new CustomException("开方医生信息获取异常:"+437L);
        }

        fsPrescribe.setPrescribeDoctorId(fsDoctor.getDoctorId());
        fsPrescribe.setPrescribeDoctorSignUrl(fsDoctor.getSignUrl());

        //分配在线的随机药师
        fsPrescribe.setDrugDoctorId(514L);
        fsPrescribe.setDrugDoctorSignUrl("https://ysy-1329817240.cos.ap-guangzhou.myqcloud.com/ysy/20251114/7a0d28df6aa94a9c819e025c9a230c6f.png");
//        FsDoctor fsDrugDoctor = null;
//        try {
//            // 使用新写的轮询服务分配药师，传入处方编号
//            fsDrugDoctor = pollingAssignDoctorService.getNextPharmacist(prescribeCode);
//
//            fsPrescribe.setDrugDoctorId(fsDrugDoctor.getDoctorId());
//            fsPrescribe.setDrugDoctorSignUrl(fsDrugDoctor.getSignUrl());
//
//            log.info("超拼网轮询分配药师成功 - 处方号:{}, 药师ID:{}, 药师姓名:{}",
//                    prescribeCode, fsDrugDoctor.getDoctorId(), fsDrugDoctor.getDoctorName());
//        } catch (Exception e) {
//            log.error("超拼网患者-分配药师失败 - 处方号:{}", prescribeCode, e);
//            fsPrescribe.setDrugDoctorId(1L);//为了不影响主业务执行设置默认值
//        }
        return fsPrescribe;
    }

    @Override
    public SubmitUserInformationVO createUserInformationCPW(CPWUserAndAddressAddDTO cpwUserAndAddressAddDTO) {
        SubmitUserInformationVO resultVO=new SubmitUserInformationVO();
        //创建fs_user用户信息
        CPWUserBaseInfoAddDTO userBaseInfo = cpwUserAndAddressAddDTO.getUserBaseInfo();
        FsUser queryCondition = new FsUser();
        queryCondition.setIdCard(userBaseInfo.getIdCard());
        List<FsUser> fsUsers = fsUserMapper.selectFsUserList(queryCondition);
        if (CollectionUtils.isNotEmpty(fsUsers)){
            throw new CustomException("用户信息保存失败，用户已存在", 500);
        }
        FsUser addFsUser = transformUserDtoToFsUser(userBaseInfo);
        int addResult1 = fsUserMapper.insertFsUser(addFsUser);
        if (addResult1 <= 0) {
            throw new CustomException("用户信息保存失败", 500);
        }
        //新增fs_user_address用户地址信息
        FsUserAddress address=buildUserAddress(cpwUserAndAddressAddDTO.getAddress(),addFsUser);
        int addResult2 = fsUserAddressMapper.insertFsUserAddress(address);
        if (addResult2 <= 0) {
            throw new CustomException("用户地址信息保存失败", 500);
        }
        resultVO.setStatus(BigDecimal.ONE.intValue());
        resultVO.setMessage("提交成功");
        resultVO.setSubmitTime(DateUtils.getTime());
        return resultVO;
    }

    @Override
    //@Transactional(rollbackFor = Exception.class)
    public SubmitUserInformationVO submitUserInformation(CPWUserInfoCollectionAddDTO collectionAddDTO) {
        //新增fs_user_information_collection用户采集信息
        Long userId = collectionAddDTO.getPatientInfo().getPatientId();
        FsUser fsUserQueryCondition=new FsUser();
        fsUserQueryCondition.setUserId(userId);
        fsUserQueryCondition.setUserSource(2);//超拼网用户
        List<FsUser> fsUsers = fsUserMapper.selectFsUserList(fsUserQueryCondition);
        if (CollectionUtils.isEmpty(fsUsers)) {
            log.error("超拼网提交用户采集信息,用户不存在，用户id:{}", userId);
            throw new CustomException("用户不存在", 500);
        }
        FsUserInformationCollection fsUserInformationCollection = transformUserDtoToFsUserCollection(collectionAddDTO,fsUsers.get(0));
        int addResult = fsUserInformationCollectionMapper.insertFsUserInformationCollection(fsUserInformationCollection);
        if (addResult <= 0) {
            throw new CustomException("采集信息保存失败", 500);
        }
        //构建成功返回结果
        SubmitUserInformationVO resultVO = new SubmitUserInformationVO();
        resultVO.setCollectionId(fsUserInformationCollection.getId());
        resultVO.setStatus(BigDecimal.ONE.intValue());
        resultVO.setMessage("提交成功");
        resultVO.setSubmitTime(DateUtils.getTime());
        log.info("超拼网---用户采集信息提交成功，userId: {}, collectionId: {}",
                userId, fsUserInformationCollection.getId());
        return resultVO;
    }

    @Override
    public int prescriptionReceipt(List<Long> prescriptionIds) {
        if (CollectionUtils.isEmpty(prescriptionIds)){
            return 0;
        }
        log.info("超拼网-推送回执处方id:{}", prescriptionIds);
        return prescribeMapper.updateFsPrescribeListDataCPWByPrescribeIds(prescriptionIds);
    }

    @Override
    public List<CPWPrescribeDataVO> pushPrescription() {
        // 获取待推送到"超拼网"的处方数据
        List<FsPrescribe> fsPrescribes = prescribeMapper.selectFsPrescribeListDataPushCPW();

        if (CollectionUtils.isEmpty(fsPrescribes)) {
            log.info("无待推送超拼网的处方");
            return new ArrayList<>();
        }

        // 获取所有处方的ID列表
        List<Long> prescribeIds = fsPrescribes.stream()
                .map(FsPrescribe::getPrescribeId)
                .collect(Collectors.toList());

        // 批量查询药品信息
        List<FsPrescribeDrug> prescribeDrugList = prescribeDrugMapper.selectFsPrescribeDrugListByPrescribeIds(prescribeIds);

        // 按处方ID分组药品
        Map<Long, List<FsPrescribeDrug>> prescribeDrugMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(prescribeDrugList)) {
            prescribeDrugMap = prescribeDrugList.stream()
                    .collect(Collectors.groupingBy(FsPrescribeDrug::getPrescribeId));
        }

        // 组装返回结果
        List<CPWPrescribeDataVO> resultList = new ArrayList<>();
        for (FsPrescribe item : fsPrescribes) {
            CPWPrescribeDataVO resultVO = new CPWPrescribeDataVO();
            resultVO.setPatientId(item.getPatientId());
            resultVO.setPatientName(item.getPatientName());
            resultVO.setPrescribeImgUrl(item.getPrescribeImgUrl());

            // 获取该处方的药品列表并转换为VO
            List<FsPrescribeDrug> drugList = prescribeDrugMap.getOrDefault(item.getPrescribeId(), new ArrayList<>());
            List<CPWPrescribeDrugVO> drugVOList = convertToCPWPrescribeDrugVO(drugList);
            resultVO.setDrugList(drugVOList);

            resultList.add(resultVO);
        }

        return resultList;
    }

    /**
     * 将FsPrescribeDrug转换为CPWPrescribeDrugVO
     */
    private List<CPWPrescribeDrugVO> convertToCPWPrescribeDrugVO(List<FsPrescribeDrug> drugList) {
        if (CollectionUtils.isEmpty(drugList)) {
            return new ArrayList<>();
        }

        return drugList.stream().map(drug -> {
            CPWPrescribeDrugVO vo = new CPWPrescribeDrugVO();
            vo.setPrescribeId(drug.getPrescribeId());
            vo.setDrugName(drug.getDrugName());
            vo.setDrugSpec(drug.getDrugSpec());
            vo.setUsageMethod(drug.getUsageMethod());
            vo.setUsageFrequencyUnit(drug.getUsageFrequencyUnit());
            vo.setUsagePerUseCount(drug.getUsagePerUseCount());
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 转换用户采集信息fs_user_information_collection
     * */
    private FsUserInformationCollection transformCollectionDtoToFsUserCollection(CPWUserInfoCollectionAddDTO collectionAddDTO) {
        CPWPatientInfoAddDTO patientInfo = collectionAddDTO.getPatientInfo();
        FsUserInformationCollection fsUserInformationCollection=new FsUserInformationCollection();
        fsUserInformationCollection.setThirdPartyUserId(collectionAddDTO.getPatientInfo().getPatientId());
        fsUserInformationCollection.setQuestionId(QUESTION_ID);
        fsUserInformationCollection.setUserName(collectionAddDTO.getPatientInfo().getPatientName());
        fsUserInformationCollection.setUserPhoneFour(patientInfo.getPatientTel().substring(patientInfo.getPatientTel().length()-4));//手机号后四位
        fsUserInformationCollection.setSex(convertGenderToLong(patientInfo.getPatientGender()));
        fsUserInformationCollection.setAge(calculateAge(patientInfo.getPatientBirthday()));//年龄
        fsUserInformationCollection.setAllergy(collectionAddDTO.getAllergy());
        fsUserInformationCollection.setRemark(collectionAddDTO.getRemark());
        fsUserInformationCollection.setInfoSource(2);//采集信息来源：超拼网用户
        fsUserInformationCollection.setCreateTime(DateUtils.getNowDate());
        fsUserInformationCollection.setUserConfirm(BigDecimal.ZERO.intValue());//用户第一次确认 0-未确认 1-已确认
        fsUserInformationCollection.setUserConfirm2(BigDecimal.ZERO.intValue());//用户第二次确认 0-未确认 1-已确认
        fsUserInformationCollection.setDoctorConfirm(BigDecimal.ZERO.intValue());//医生确认开方 0-未确认 1-已确认
        fsUserInformationCollection.setJsonInfo(JSON.toJSONString(collectionAddDTO.getAnswers()));//采集信息
        return fsUserInformationCollection;
    }
    /**
     * 转换用户信息fs_user
     * */
    private FsUser transformUserDtoToFsUser(CPWUserBaseInfoAddDTO userBaseInfo) {
        FsUser fsUser=new FsUser();
        fsUser.setRealName(userBaseInfo.getName());
        fsUser.setNickname("超拼网用户:"+userBaseInfo.getName()+userBaseInfo.getUserPhone().substring(userBaseInfo.getUserPhone().length()-4));
        fsUser.setIdCard(userBaseInfo.getIdCard());
        fsUser.setUserSource(2);//超拼网用户
        fsUser.setIsDel(BigDecimal.ZERO.intValue());
        fsUser.setStatus(BigDecimal.ONE.intValue());
        fsUser.setCreateTime(DateUtils.getNowDate());
        fsUser.setPhone(userBaseInfo.getUserPhone());
        return fsUser;
    }

    /**
     *  构建用户地址信息
     * */
    private FsUserAddress buildUserAddress(FsUserAddress fsUserAddress,FsUser addFsUser) {
        fsUserAddress.setUserId(addFsUser.getUserId());
        fsUserAddress.setPhone(addFsUser.getPhone());
        fsUserAddress.setDetail(fsUserAddress.getDetail().trim());
        fsUserAddress.setCreateTime(DateUtils.getNowDate());
        fsUserAddress.setIsDefault(BigDecimal.ONE.intValue());
        fsUserAddress.setIsDel(BigDecimal.ZERO.intValue());
        return fsUserAddress;
    }

    /**
     * 转换用户采集信息fs_user_information_collection
     * */
    private FsUserInformationCollection transformUserDtoToFsUserCollection(CPWUserInfoCollectionAddDTO collectionAddDTO,FsUser fsUser) {
        FsUserInformationCollection fsUserInformationCollection=new FsUserInformationCollection();
        fsUserInformationCollection.setThirdPartyUserId(collectionAddDTO.getPatientInfo().getPatientId());
        fsUserInformationCollection.setQuestionId(QUESTION_ID);
        fsUserInformationCollection.setUserName(fsUser.getRealName());
        fsUserInformationCollection.setUserPhoneFour(fsUser.getPhone().substring(fsUser.getPhone().length()-4));//手机号后四位
        fsUserInformationCollection.setSex((long) IdCardUtil.getGenderByIdCard(fsUser.getIdCard()));
        fsUserInformationCollection.setAge(IdCardUtil.getAgeByIdCard(fsUser.getIdCard()));//年龄
        fsUserInformationCollection.setAllergy(collectionAddDTO.getAllergy());
        fsUserInformationCollection.setRemark(collectionAddDTO.getRemark());
        fsUserInformationCollection.setInfoSource(2);//超拼网用户采集信息
        fsUserInformationCollection.setCreateTime(DateUtils.getNowDate());
        fsUserInformationCollection.setUserConfirm(BigDecimal.ZERO.intValue());//用户第一次确认 0-未确认 1-已确认
        fsUserInformationCollection.setUserConfirm2(BigDecimal.ZERO.intValue());//用户第二次确认 0-未确认 1-已确认
        fsUserInformationCollection.setDoctorConfirm(BigDecimal.ZERO.intValue());//医生确认开方 0-未确认 1-已确认
        fsUserInformationCollection.setJsonInfo(JSON.toJSONString(collectionAddDTO.getAnswers()));//采集信息
        return fsUserInformationCollection;
    }

    /**
     * 根据出生日期计算年龄
     * @param birthday 出生日期，格式：yyyy-MM-dd
     * @return Integer类型的年龄，如果入参无效返回null
     */
    public static Integer calculateAge(String birthday) {
        if (StringUtils.isBlank(birthday)) {
            return null;
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            sdf.setLenient(false);
            Date birthDate = sdf.parse(birthday);

            Calendar birthCal = Calendar.getInstance();
            birthCal.setTime(birthDate);

            Calendar nowCal = Calendar.getInstance();

            int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

            // 如果今年还没过生日，年龄减1
            if (nowCal.get(Calendar.MONTH) < birthCal.get(Calendar.MONTH) ||
                    (nowCal.get(Calendar.MONTH) == birthCal.get(Calendar.MONTH) &&
                            nowCal.get(Calendar.DAY_OF_MONTH) < birthCal.get(Calendar.DAY_OF_MONTH))) {
                age--;
            }

            return age;

        } catch (ParseException e) {
            throw new CustomException("用户年龄计算异常", 500);
        }
    }

    /**
     * 将性别字符转换为Long类型
     * @param gender 性别字符："1"表示男，"2"表示女
     * @return "1"返回1L，"2"返回0L，其他情况返回null
     */
    public static Long convertGenderToLong(String gender) {
        if (StringUtils.isBlank(gender)) {
            return null;
        }

        switch (gender) {
            case "1":
                return 1L;
            case "2":
                return 0L;
            default:
                throw new CustomException("用户性别数入异常", 500);
        }
    }
}
