package com.fs.his.service.impl;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.event.TemplateBean;
import com.fs.event.TemplateEvent;
import com.fs.event.TemplateListenEnum;
import com.fs.his.domain.*;
import com.fs.his.mapper.*;
import com.fs.his.param.FsInquiryOrderReportParam;
import com.fs.his.param.FsStoreOrderParam;
import com.fs.his.service.IFsInquiryDiseaseService;
import com.fs.his.vo.FsInquiryDiseaseVO;
import com.fs.his.vo.FsInquiryOrderReportListVO;
import com.fs.his.vo.FsInquiryOrderReportUVO;
import com.fs.his.vo.FsInquiryOrderReportVO;
import com.fs.jpush.service.JpushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.fs.his.service.IFsInquiryOrderReportService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问诊报告Service业务层处理
 *
 * @author fs
 * @date 2023-09-04
 */
@Service
public class FsInquiryOrderReportServiceImpl implements IFsInquiryOrderReportService
{

    @Autowired
    private ApplicationEventPublisher publisher;

    @Autowired
    private JpushService jpushService;
    @Autowired
    private FsInquiryOrderReportMapper fsInquiryOrderReportMapper;

    @Autowired
    private FsInquiryOrderMapper fsInquiryOrderMapper;
    @Autowired
    private FsDoctorMapper fsDoctorMapper;

    @Autowired
    private FsInquiryDiseaseMapper fsInquiryDiseaseMapper;
    /**
     * 查询问诊报告
     *
     * @param reportId 问诊报告主键
     * @return 问诊报告
     */
    @Override
    public FsInquiryOrderReport selectFsInquiryOrderReportByReportId(Long reportId)
    {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportByReportId(reportId);
    }

    /**
     * 查询问诊报告列表
     *
     * @param fsInquiryOrderReport 问诊报告
     * @return 问诊报告
     */
    @Override
    public List<FsInquiryOrderReport> selectFsInquiryOrderReportList(FsInquiryOrderReport fsInquiryOrderReport)
    {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportList(fsInquiryOrderReport);
    }

    /**
     * 新增问诊报告
     *
     * @param fsInquiryOrderReport 问诊报告
     * @return 结果
     */
    @Override
    public int insertFsInquiryOrderReport(FsInquiryOrderReport fsInquiryOrderReport)
    {
        fsInquiryOrderReport.setCreateTime(DateUtils.getNowDate());
        FsDoctor drug =fsDoctorMapper.selectPackageFsDoctorType2Ids(2);
        fsInquiryOrderReport.setDrugId(drug.getDoctorId());
        fsInquiryOrderReport.setDrugDoctorSignUrl(drug.getSignUrl());
        return fsInquiryOrderReportMapper.insertFsInquiryOrderReport(fsInquiryOrderReport);
    }

    /**
     * 修改问诊报告
     *
     * @param fsInquiryOrderReport 问诊报告
     * @return 结果
     */
    @Override
    public int updateFsInquiryOrderReport(FsInquiryOrderReport fsInquiryOrderReport)
    {
//        fsInquiryOrderReport.setUpdateTime(DateUtils.getNowDate());
        return fsInquiryOrderReportMapper.updateFsInquiryOrderReport(fsInquiryOrderReport);
    }

    /**
     * 批量删除问诊报告
     *
     * @param reportIds 需要删除的问诊报告主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderReportByReportIds(Long[] reportIds)
    {
        return fsInquiryOrderReportMapper.deleteFsInquiryOrderReportByReportIds(reportIds);
    }

    /**
     * 删除问诊报告信息
     *
     * @param reportId 问诊报告主键
     * @return 结果
     */
    @Override
    public int deleteFsInquiryOrderReportByReportId(Long reportId)
    {
        return fsInquiryOrderReportMapper.deleteFsInquiryOrderReportByReportId(reportId);
    }

    @Override
    public List<FsInquiryOrderReportListVO> selectFsInquiryOrderReportListVO(FsInquiryOrderReportParam fsInquiryOrderReport) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportListVO(fsInquiryOrderReport);
    }

    @Override
    public FsInquiryOrderReportVO selectFsInquiryOrderReportByReportIdVO(Long reportId) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportByReportIdVO(reportId);
    }

    @Transactional
    @Override
    public int updateFsInquiryOrderReportAudit(FsInquiryOrderReport fsInquiryOrderReport) {
        fsInquiryOrderReport.setUpdateTime(DateUtils.getNowDate());
        fsInquiryOrderReport.setStatus(1);
        FsInquiryOrderReportVO order = fsInquiryOrderReportMapper.selectFsInquiryOrderReportByReportIdVO(fsInquiryOrderReport.getReportId());
        fsInquiryOrderReport.setPatientJson(order.getPatientJson());
        if (order.getStatus()!=0){
            throw new CustomException("报告已被处理");
        }
        FsInquiryOrder inquiryOrder = fsInquiryOrderMapper.selectFsInquiryOrderByOrderId(order.getOrderId());
        if (inquiryOrder==null){
            throw new CustomException("问诊订单不存在");
        }
        inquiryOrder.setAuditTime(DateUtils.getNowDate());
        inquiryOrder.setIsAudit(1);
        inquiryOrder.setAuditUserId(fsInquiryOrderReport.getAuditUserId());

        if (fsInquiryOrderReport.getDoctorId()!=null){
            inquiryOrder.setIsReceive(1);
            fsInquiryOrderReport.setDoctorSignUrl(order.getSignUrl());
            inquiryOrder.setDoctorId(fsInquiryOrderReport.getDoctorId());
            FsDoctor doctor=fsDoctorMapper.selectFsDoctorByDoctorId(fsInquiryOrderReport.getDoctorId());
            if(doctor==null){
                throw new CustomException("所选医生异常");
            }
            if(StringUtils.isNotEmpty(doctor.getJpushId())){
                Map<String, String> extrasMap=new HashMap<>();
                extrasMap.put("orderId",order.getOrderId().toString());
                extrasMap.put("type","order");
                try {
                    jpushService.sendRegisterIdPush("问诊订单消息","您有一个新的问诊订单",extrasMap,doctor.getJpushId());
                } catch (APIConnectionException e) {
                } catch (APIRequestException e) {
                }
            }

        }else {
            inquiryOrder.setIsReceive(0);
        }
        TemplateBean templateBean = TemplateBean.builder()
                .orderId(order.getOrderId().toString())
                .title("订单号"+inquiryOrder.getOrderSn()+"已接单")
                .remark("您的订单医生已接单")
                .uid(order.getUserId())
                .templateType(TemplateListenEnum.TYPE_2.getValue())
                .build();
        publisher.publishEvent(new TemplateEvent(this, templateBean));
        fsInquiryOrderMapper.updateFsInquiryOrder(inquiryOrder);
        return fsInquiryOrderReportMapper.updateFsInquiryOrderReport(fsInquiryOrderReport);
    }

    @Override
    public Integer selectFsInquiryOrderReportIdByOrderId(Long id) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportIdByOrderId(id);
    }

    @Override
    public String selectFsTestBody() {
        return fsInquiryOrderReportMapper.selectFsTestBody();
    }

    @Override
    public FsInquiryOrderReportUVO selectFsInquiryOrderReportUVOByOrderId(Long orderId) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportUVOByOrderId(orderId);
    }

    @Override
    public FsInquiryOrderReportVO selectFsInquiryOrderReportByOrderIdVO(Long code) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportByOrderIdVO(code);
    }

    @Override
    public Boolean isEntityNull(FsInquiryOrderReportParam param) {
        if (param == null) {
            return true; // 整个实体对象为null
        }

        Class<? extends FsInquiryOrderReportParam> entityClass = param.getClass();
        Field[] fields = entityClass.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(param);
                if (value != null) {
                    return false; // 实体对象中有字段不为null
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return true; // 实体对象内所有字段为null
    }

    @Override
    public Long selectFsInquiryOrderReportListVOCount(FsInquiryOrderReportParam fsInquiryOrderReport) {
       return fsInquiryOrderReportMapper.selectFsInquiryOrderReportListVOCount(fsInquiryOrderReport);
    }
    @Autowired
    FsExportTaskMapper fsExportTaskMapper;


    @Override
    public FsInquiryOrderReport selectFsInquiryOrderReportByOrderId(Long orderId) {
        return fsInquiryOrderReportMapper.selectFsInquiryOrderReportByOrderId(orderId);
    }


    @Async
    @Override
    public void exportData(FsInquiryOrderReportParam fsInquiryOrderReport) {
        List<FsInquiryDiseaseVO> fsInquiryDiseaseVOS = fsInquiryDiseaseMapper.selectFsInquiryDiseaseListVO(new FsInquiryDisease());
        List<FsInquiryOrderReportListVO> list = fsInquiryOrderReportMapper.selectFsInquiryOrderReportListVO(fsInquiryOrderReport);


        for (FsInquiryOrderReportListVO vo : list){
            if (vo.getPhone()!=null&&vo.getPhone()!=""){
                vo.setPhone(vo.getPhone().replaceAll("(\\d{3})\\d*(\\d{4})", "$1****$2"));
            }
            if (vo.getDiseaseType()!=null&&vo.getDiseaseType()!=""){
                String diseaseType = vo.getDiseaseType();
                String[] split = diseaseType.split(",");
                String name="";
                for (String s : split) {
                    for (FsInquiryDiseaseVO fsInquiryDiseaseVO : fsInquiryDiseaseVOS) {
                        if (fsInquiryDiseaseVO.getDictValue().equals(s)){
                            name+=fsInquiryDiseaseVO.getDictLabel()+",";
                        }
                    }
                }
                if(name.length() > 0) {
                    vo.setDiseaseName(name.substring(0, name.length() - 1));
                }

            }
        }
        ExcelUtil<FsInquiryOrderReportListVO> util = new ExcelUtil<FsInquiryOrderReportListVO>(FsInquiryOrderReportListVO.class);
        AjaxResult result =  util.exportExcel(list, "咨询报告数据");
        FsExportTask task=fsExportTaskMapper.selectFsExportTaskByTaskId(fsInquiryOrderReport.getTaskId());
        task.setFinishTime(new Date());
        task.setStatus(1);
        task.setFileUrl(result.get("msg").toString());
        fsExportTaskMapper.updateFsExportTask(task);

    }

}
