package cn.hnthyy.thmz.service.impl.thmz;

import cn.hnthyy.thmz.common.Constants;
import cn.hnthyy.thmz.entity.his.mz.*;
import cn.hnthyy.thmz.entity.his.zd.ZdUnitCode;
import cn.hnthyy.thmz.enums.OrderStatusEnum;
import cn.hnthyy.thmz.enums.PayMarkEnum;
import cn.hnthyy.thmz.pageDto.MzChargeDetailPageDto;
import cn.hnthyy.thmz.service.his.mz.*;
import cn.hnthyy.thmz.service.his.zd.ZdUnitCodeService;
import cn.hnthyy.thmz.service.thmz.HaiCiAdapterService;
import cn.hnthyy.thmz.service.thmz.OrderStatusChangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class OrderStatusChangeServiceImpl implements OrderStatusChangeService {
    @Autowired
    private HaiCiAdapterService haiCiAdapterService;
    @Autowired
    private MzPatientMiService mzPatientMiService;
    @Autowired
    private MzyReqrecService mzyReqrecService;
    @Autowired
    private ZdUnitCodeService zdUnitCodeService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private MzChargeDetailService mzChargeDetailService;
    @Autowired
    private MzYjReqService mzYjReqService;
    //就诊状态通知开关
    @Value("${sendNoticeToPatient}")
    private boolean sendNoticeToPatient;

    private ExecutorService executor = Executors.newFixedThreadPool(5);


    @Override
    public void orderStatusChange(String text) {
        executor.submit(() -> {
            try {
                if (!sendNoticeToPatient) {
                    return;
                }
                if (StringUtils.isBlank(text)) {
                    return;
                }
                String[] arr = text.split(",");
                if (arr == null || arr.length == 0) {
                    return;
                }
                String[] patientInfo = arr[0].split("_");
                if (patientInfo == null || patientInfo.length == 0) {
                    return;
                }
                MzPatientMi mzPatientMi = mzPatientMiService.queryByPatientId(patientInfo[0]);
                if (mzPatientMi == null || StringUtils.isBlank(mzPatientMi.getIcCardNo())) {
                    return;
                }
                String status = arr[1];
                if (OrderStatusEnum.REGISTRATION_SUCCESS.code.equals(status)) {
                    MzyReqrec mzyReqrec = mzyReqrecService.queryMzyReqrecByPatientIdAndTimes(patientInfo[0], Integer.valueOf(patientInfo[1]));
                    if (mzyReqrec == null) {
                        return;
                    }
                    if (StringUtils.isBlank(mzyReqrec.getUnitCode())) {
                        return;
                    }
                    ZdUnitCode zdUnitCode = zdUnitCodeService.queryByCode(mzyReqrec.getUnitCode());
                    if (zdUnitCode == null) {
                        return;
                    }
                    String doctorName = "";
                    if (StringUtils.isNotBlank(mzyReqrec.getDoctorCode())) {
                        Employee employee = employeeService.queryByUserCode(mzyReqrec.getDoctorCode());
                        if (employee != null) {
                            doctorName = employee.getEmployeeName();
                        }
                    }
                    haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您已经挂号成功,请您及时前往医生诊室就诊，详情如下:\"},\"deptname\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getName() + "\"},\"doctorname\":{\"color\":\"#173177\",\"value\":\"" + doctorName + "\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\"就诊地点 : " + zdUnitCode.getOfficePos() + "。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"ctMSV4jb3aHYJS0hOjTl8h9Nyrj-46XTLMnUFn6eWh8\",\"touser\":\"\",\"url\":\"\"}", new Date());
                    return;
                }
                if (OrderStatusEnum.SUCCESSFUL_PRESCRIPTION_PAYMENT.code.equals(status)) {
                    MzChargeDetailPageDto mzChargeDetailPageDto = new MzChargeDetailPageDto();
                    MzChargeDetail mzChargeDetailParams = new MzChargeDetail(patientInfo[0], Integer.valueOf(patientInfo[1]));
                    mzChargeDetailParams.setReceiptNo(Integer.valueOf(patientInfo[2]));
                    mzChargeDetailParams.setPayMark(PayMarkEnum.CHARGED.code);
                    mzChargeDetailPageDto.setMzChargeDetail(mzChargeDetailParams);
                    List<MzChargeDetail> mzChargeDetailList = mzChargeDetailService.queryMzChargeDetailWithPage(mzChargeDetailPageDto);
                    if (mzChargeDetailList == null || mzChargeDetailList.size() == 0) {
                        return;
                    }
                    MzChargeDetail mzChargeDetail = mzChargeDetailList.get(0);
                    if (mzChargeDetail == null) {
                        return;
                    }
                    if (StringUtils.isBlank(mzChargeDetail.getWarnDept())) {
                        return;
                    }
                    ZdUnitCode zdUnitCode = zdUnitCodeService.queryByCode(mzChargeDetail.getWarnDept());
                    if (zdUnitCode == null) {
                        return;
                    }
                    if (mzChargeDetail.getAmount() != null) {
                        mzChargeDetail.setAmount(mzChargeDetail.getAmount().setScale(1, BigDecimal.ROUND_HALF_UP));
                    }
                    String doctorName = "";
                    if (StringUtils.isNotBlank(mzChargeDetail.getDoctorCode())) {
                        Employee employee = employeeService.queryByUserCode(mzChargeDetail.getDoctorCode());
                        if (employee != null) {
                            doctorName = employee.getEmployeeName();
                        }
                    }
                    haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您本次缴费账单消息：\"},\"keynote1\":{\"color\":\"#173177\",\"value\":\"" + mzChargeDetail.getName() + "\"},\"keynote2\":{\"color\":\"#173177\",\"value\":\"" + arr[0] + "\"},\"keynote3\":{\"color\":\"#173177\",\"value\":\"" + mzChargeDetail.getAmount() + "\"},\"keynote4\":{\"color\":\"#173177\",\"value\":\"" + doctorName + "\"},\"keynote5\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getName() + "\"},\"keynote6\":{\"color\":\"#173177\",\"value\":\"湖南泰和医院\"},\"keynote7\":{\"color\":\"#173177\",\"value\":\"" + DateFormatUtils.format(mzChargeDetail.getChargeDate(), "yyyy-MM-dd HH:mm:ss") + "\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\" 缴费已成功，湖南泰和医院祝您身体健康。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"IGc0AXcLvxD7TUvtjH4EA91xQppYMKBYObHXayBNd6A\",\"touser\":\"\",\"url\":\"\"}", new Date());
                    MzYjReq mzYjReq = new MzYjReq(patientInfo[0], Integer.valueOf(patientInfo[1]));
                    mzYjReq.setReceiptNo(Integer.valueOf(patientInfo[2]));
                    List<String> execDeps = mzYjReqService.queryExecDept(mzYjReq);
                    if (execDeps == null || execDeps.size() == 0) {
                        return;
                    }
                    for (String str : execDeps) {
                        zdUnitCode = zdUnitCodeService.queryByCode(str);
                        if (zdUnitCode == null) {
                            continue;
                        }
                        if ("2010000".equals(str)) {
                            //检验
                            haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您已完成缴费，请到指定地点进行检验检查。\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getName() + "\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getOfficePos() + "\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\" 抽血室在一楼急诊科，大小便标本在门诊大楼三楼医学检验科，核酸检测采样室在二楼1号诊室。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"amY5BinXb2IpwdXqcOyXxtZZ26XyQOIQ3j1ablSWxy0\",\"touser\":\"\",\"url\":\"\"}", new Date());
                        } else {
                            //检查
                            haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您已完成缴费，请到指定地点进行检验检查。\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getName() + "\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"" + zdUnitCode.getOfficePos() + "\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\" 感谢您的使用。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"amY5BinXb2IpwdXqcOyXxtZZ26XyQOIQ3j1ablSWxy0\",\"touser\":\"\",\"url\":\"\"}", new Date());
                        }

                    }
                    List<String> groupNos = mzChargeDetailService.queryGroupNo(mzChargeDetailParams);
                    if (groupNos == null || groupNos.size() == 0) {
                        return;
                    }
                    for (String str : groupNos) {
                        if (Constants.XY_ZCY_GROUP_NO.equals(str)) {
                            haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您已完成缴费，请到指定地点取药。\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"门诊西药房\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"门诊大楼一楼\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\" 感谢您的使用。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"amY5BinXb2IpwdXqcOyXxtZZ26XyQOIQ3j1ablSWxy0\",\"touser\":\"\",\"url\":\"\"}", new Date());
                        } else if (Constants.ZY_GROUP_NO.equals(str)) {
                            haiCiAdapterService.commonMessageNotice(mzPatientMi.getIcCardNo(), "{\"data\":{\"first\":{\"color\":\"#FF0000\",\"value\":\"您好，您已完成缴费，请到指定地点取药。\"},\"keyword1\":{\"color\":\"#173177\",\"value\":\"门诊中药房\"},\"keyword2\":{\"color\":\"#173177\",\"value\":\"门诊大楼一楼\"},\"remark\":{\"color\":\"#FF0000\",\"value\":\" 感谢您的使用。\"}},\"miniprogram\":{\"appid\":\"\",\"pagepath\":\"\"},\"template_id\":\"amY5BinXb2IpwdXqcOyXxtZZ26XyQOIQ3j1ablSWxy0\",\"touser\":\"\",\"url\":\"\"}", new Date());
                        }
                    }
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("海慈消息调用失败", e.getMessage());
            }
        });
    }

}
