package com.saye.hospitalgd.scheduler.jobMethod;

import com.saye.hospitalgd.commons.date.DateDUtil;
import com.saye.hospitalgd.commons.getBean.GetBeanUtil;
import com.saye.hospitalgd.commons.log.LogUtil;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.model.Dicinfo;
import com.saye.hospitalgd.service.HisDetailService;
import com.saye.hospitalgd.service.HisInterFaceConfigService;
import com.saye.hospitalgd.service.OperatorService;
import com.saye.hospitalgd.service.historyLog.HisBillLogService;
import com.saye.hospitalgd.service.historyLog.impl.HisBillLogServiceImpl;
import com.saye.hospitalgd.service.impl.HisDetailServiceImpl;
import com.saye.hospitalgd.service.impl.HisInterFaceConfigServiceImpl;
import com.saye.hospitalgd.service.impl.OperatorServiceImpl;
import com.saye.hospitalgd.service.system.DicinfoService;
import com.saye.hospitalgd.service.system.ServiceParamsService;
import com.saye.hospitalgd.service.system.impl.DicinfoServiceImpl;
import com.saye.hospitalgd.service.system.impl.ServiceParamsServiceImpl;
import com.saye.hospitalgd.util.HisUtil;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author thuang
 * @version 1.0
 * @description: His获取数据方法（弘扬）
 * @date 2021/9/30 13:41
 */
public class HISGetDataMethodByHY {

    public HashMap<Object,Object> getDate(String id,String name,String trade_date,String his_wsdl_id){
        HashMap<Object,Object> responseMap=new HashMap<>();
        String errCode="0";
        String errMsg="";

        HisBillLogService hisBillLogService = GetBeanUtil.getBean(HisBillLogServiceImpl.class);
        HisDetailService hisDetailService = GetBeanUtil.getBean(HisDetailServiceImpl.class);
        OperatorService operatorService = GetBeanUtil.getBean(OperatorServiceImpl.class);
        DicinfoService dicinfoService = GetBeanUtil.getBean(DicinfoServiceImpl.class);

        ServiceParamsService serviceParamsService = GetBeanUtil.getBean(ServiceParamsServiceImpl.class);

        HisInterFaceConfigService hisInterFaceConfigService = GetBeanUtil.getBean(HisInterFaceConfigServiceImpl.class);

        try {
            //查询需要用到的参数

            //his接口地址
            List<HashMap<Object, Object>> hisConfigList = hisInterFaceConfigService.findConfigById(his_wsdl_id);
            String his_wsdl = StringDUtil.changeNullToEmpty(hisConfigList.get(0).get("HIS_INTERFACE_WSDL"));
            String code = StringDUtil.changeNullToEmpty(hisConfigList.get(0).get("CODE"));

            //现金支付方式
            List<HashMap<Object, Object>> serviceParams = serviceParamsService.findParamValByParamCode("cash_code");
            String cash_code = StringDUtil.changeNullToEmpty(serviceParams.get(0).get("PARAM_VAL"));

            //his端其他支付方式 也单独处理 因为里面没有唯一id 且都是支票记录
            String zhipiao="无";

            //操作员号
            List<HashMap<Object,Object>> operators = operatorService.findAllOperator(new HashMap<Object,Object>());
            //将操作员号用逗号连接
            String operatorsCodeStr="";
            for (int i = 0; i < operators.size(); i++) {
                HashMap<Object, Object> hashMap = operators.get(i);
                operatorsCodeStr =operatorsCodeStr + StringDUtil.changeNullToEmpty(hashMap.get("HISOPERCODE")) + ",";
            }
            if (operatorsCodeStr.length()>0){
                operatorsCodeStr=operatorsCodeStr.substring(0,operatorsCodeStr.length()-1);
            }

            //全部支付方式
            List<Dicinfo> pay_type = dicinfoService.findDicinfoTreeNodeList("PAY_TYPE");
            HashMap<String,String> payTypeMap=new HashMap<>();
            for (Dicinfo dicinfo : pay_type) {
                payTypeMap.put( dicinfo.getDicname(),dicinfo.getDicvalue());
            }

            //开始结束时间
            String startTime="";
            String endTime="";
            if ("".equals(trade_date)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DATE, -1);
                Date time = calendar.getTime();

                startTime = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, time) + " 00:00:00";
                endTime = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, new Date()) + " 00:00:00";
                trade_date=DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, time);
            }else {
                startTime = trade_date + " 00:00:00";
                Date date = DateDUtil.strToDate(DateDUtil.yyyy_MM_dd, trade_date);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE, 1);
                endTime = DateDUtil.DateToStr(DateDUtil.yyyy_MM_dd, calendar.getTime()) + " 00:00:00";
            }

            //组织request
            String requestStr="";
            requestStr="<Request>" +
                    " <HisOperNum>"+ operatorsCodeStr +"</HisOperNum>" +
                    " <StartTime>"+startTime+"</StartTime>" +
                    " <EndTime>"+endTime+"</EndTime>" +
                    "</Request>";

            //获取数据
            HisUtil hisUtil = new HisUtil();
            HashMap<String, String> histData = hisUtil.getHisDataByHY(his_wsdl, code, requestStr);
            errCode = histData.get("errCode");
            if (!"0".equals(errCode)){
                errMsg=histData.get("errMsg");
            }else {
                String dataStr = histData.get("dataStr");

                //分析数据，判断调用正确与否
                HashMap<String, Object> hisBillResult = hisUtil.managerDataStrByHY(dataStr);
                errCode = StringDUtil.changeNullToEmpty(hisBillResult.get("errCode"));
                if (!"0".equals(errCode)){
                    errMsg=StringDUtil.changeNullToEmpty(hisBillResult.get("errMsg"));
                }else {
                    List<HashMap<Object,Object>> hisBillList  = (List<HashMap<Object,Object>>)hisBillResult.get("addList");

                    //存一份his原始的
                    hisDetailService.insertHisBillOriginalHY(hisBillList,trade_date,his_wsdl_id);

                    //将原始的转换成统一格式
                    List<HashMap<Object,Object>> newAddList= new ArrayList<>();

                    List<HashMap<Object,Object>> cashList= new ArrayList<>();

                    List<HashMap<Object,Object>> zhipiaoList= new ArrayList<>();

                    for (int i = 0; i < hisBillList.size(); i++) {
                        HashMap<Object, Object> hisBillHashMap = hisBillList.get(i);

                        //先判断关键id是否为空 ，为空的这条记录就作废了，可能之后会有现金记录进入，此id仍为空，到时需要另加判断
                        String powerTranID = StringDUtil.changeNullToEmpty(hisBillHashMap.get("powerTranID"));
                        if ("".equals(powerTranID)){
                            continue;
                        }

                        //数据类型 1-门诊 2-住院 无需修改
                        String payMethod = StringDUtil.changeNullToEmpty(hisBillHashMap.get("visitzOrg"));

                        //业务类型 0发病历1办卡2就诊卡充值3当日挂号-3 挂号退费4门诊缴费-4 单据退费5现场预约-5 预约退费6预约取号7住院缴费-7出院结算退费-77 预存作废退费
                        String bizType = StringDUtil.changeNullToEmpty(hisBillHashMap.get("bizType"));

                        String tradingStatus = "1";

                        //支付方式 修改为字典表对应
                        String payType = StringDUtil.changeNullToEmpty(hisBillHashMap.get("payType"));

                        //交易时间
                        String tradeTime = StringDUtil.changeNullToEmpty(hisBillHashMap.get("tradeTime"));

                        //操作员
                        String hisOperCode = StringDUtil.changeNullToEmpty(hisBillHashMap.get("hisOperCode"));

                        //交易金额
                        String amount = StringDUtil.changeNullToEmpty(hisBillHashMap.get("amount"));
                        try {
                            if (new BigDecimal(amount).compareTo(BigDecimal.ZERO) < 0) {
                                tradingStatus = "2";
                            }
                        } catch (Exception ex) {
                            tradingStatus = "1";
                        }

                        //说明
                        String remarks = "";

                        //银商订单号
                        String platformTransId = StringDUtil.changeNullToEmpty(hisBillHashMap.get("powerTranID"));

                        //患者 ID
                        String patientId = StringDUtil.changeNullToEmpty(hisBillHashMap.get("patientID"));

                        //患者姓名
                        String patientName = StringDUtil.changeNullToEmpty(hisBillHashMap.get("patientName"));

                        //交易日期
                        String thistrade_date = StringDUtil.changeNullToEmpty(hisBillHashMap.get("trade_date"));

                        //接口厂商
                        HashMap<Object,Object> addMap=new HashMap<>();
                        addMap.put("payMethod",payMethod);
                        addMap.put("tradingStatus",tradingStatus);
                        addMap.put("bizType",bizType);
                        addMap.put("payType",payType);
                        addMap.put("tradeTime",tradeTime);
                        addMap.put("hisOperCode",hisOperCode);
                        addMap.put("amount",amount);
                        addMap.put("remarks",remarks);
                        addMap.put("platformTransId",platformTransId);
                        addMap.put("patientId",patientId);
                        addMap.put("patientName",patientName);
                        addMap.put("trade_date",thistrade_date);
                        addMap.put("his_wsdl_id",his_wsdl_id);

                        //如果是现金记录先放进现金集合内
                        if (cash_code.equals(payType)){
                            cashList.add(addMap);
                        }else if (zhipiao.equals(payType)){
                            zhipiaoList.add(addMap);
                        }else{
                            newAddList.add(addMap);
                        }
                    }

                    //循环现金记录 合并同操作员同交易日期 同类别的（门诊，住院） his获取，记录应该就是前一天的。
                    HashMap<String,HashMap<Object,Object>> cashMap=new HashMap<>();
                    for (int i = 0; i < cashList.size(); i++) {
                        HashMap<Object, Object> hashMap = cashList.get(i);

                        String hisOperCode = StringDUtil.changeNullToEmpty(hashMap.get("hisOperCode"));
                        String payMethod = StringDUtil.changeNullToEmpty(hashMap.get("payMethod"));
                        String amount = StringDUtil.changeNullToEmpty(hashMap.get("amount"));

                        HashMap<Object, Object> map = cashMap.get(hisOperCode+"_"+payMethod);

                        if (map==null){
                            HashMap<Object,Object> addMap=new HashMap<>();
                            addMap.put("payMethod",payMethod);
                            addMap.put("tradingStatus","");
                            addMap.put("bizType","");
                            addMap.put("payType",cash_code);
                            addMap.put("tradeTime",trade_date+" 00:00:00");
                            addMap.put("hisOperCode",hisOperCode);
                            addMap.put("amount",amount);
                            addMap.put("remarks","");
                            addMap.put("platformTransId","");
                            addMap.put("patientId","");
                            addMap.put("patientName","");
                            addMap.put("trade_date",trade_date);
                            addMap.put("his_wsdl_id",his_wsdl_id);

                            cashMap.put(hisOperCode+"_"+payMethod,addMap);
                        }else {
                            String oldAmount = StringDUtil.changeNullToEmpty(map.get("amount"));
                            String newAmount = new BigDecimal(oldAmount).add(new BigDecimal(amount)).toString();
                            map.put("amount",newAmount);
                        }
                    }

                    //循环map 把记录放入要添加的集合
                    for (String key:cashMap.keySet()){
                        newAddList.add(cashMap.get(key));
                    }

                    //循环支票的记录 和现金相同处理
                    HashMap<String,HashMap<Object,Object>> zhipiaoMap=new HashMap<>();
                    for (int i = 0; i < zhipiaoList.size(); i++) {
                        HashMap<Object, Object> hashMap = zhipiaoList.get(i);

                        String hisOperCode = StringDUtil.changeNullToEmpty(hashMap.get("hisOperCode"));
                        String payMethod = StringDUtil.changeNullToEmpty(hashMap.get("payMethod"));
                        String amount = StringDUtil.changeNullToEmpty(hashMap.get("amount"));
                        String payType = StringDUtil.changeNullToEmpty(hashMap.get("payType"));

                        HashMap<Object, Object> map = zhipiaoMap.get(hisOperCode+"_"+payMethod);

                        if (map==null){
                            HashMap<Object,Object> addMap=new HashMap<>();
                            addMap.put("payMethod",payMethod);
                            addMap.put("tradingStatus","");
                            addMap.put("bizType","");
                            addMap.put("payType",payType);
                            addMap.put("tradeTime",trade_date+" 00:00:00");
                            addMap.put("hisOperCode",hisOperCode);
                            addMap.put("amount",amount);
                            addMap.put("remarks","");
                            addMap.put("platformTransId","");
                            addMap.put("patientId","");
                            addMap.put("patientName","");
                            addMap.put("trade_date",trade_date);
                            addMap.put("his_wsdl_id",his_wsdl_id);

                            zhipiaoMap.put(hisOperCode+"_"+payMethod,addMap);
                        }else {
                            String oldAmount = StringDUtil.changeNullToEmpty(map.get("amount"));
                            String newAmount = new BigDecimal(oldAmount).add(new BigDecimal(amount)).toString();
                            map.put("amount",newAmount);
                        }
                    }

                    //循环map 把记录放入要添加的集合
                    for (String key:zhipiaoMap.keySet()){
                        newAddList.add(zhipiaoMap.get(key));
                    }

                    //存一份his针对要调整的字段修改的
                    hisDetailService.insertHisBillList(newAddList,trade_date,his_wsdl_id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            errCode="999";
            errMsg="执行定时任务【"+name+"】出错，原因："+e.getMessage();
        }

        //存储记录
        try {
            HashMap<Object,Object> addMap=new HashMap<>();
            addMap.put("trade_date",trade_date);
            addMap.put("quartz_id",id);
            addMap.put("quartz_name",name);
            addMap.put("his_wsdl_id",his_wsdl_id);

            if ("0".equals(errCode)){
                addMap.put("is_ok","1");
            }else {
                addMap.put("is_ok","0");
            }

            addMap.put("modify_time",DateDUtil.getCurrentDate(DateDUtil.yyyy_MM_dd_HH_mm_ss));
            hisBillLogService.insertHisbillGetinfo(addMap);

        }catch (Exception e){
            e.printStackTrace();
            errCode="999";
            errMsg="保存His获取的记录失败，原因"+e.getMessage();
        }

        if (!"0".equals(errCode)){
            try {
                //记录日志
                LogUtil.error(this.getClass(), errMsg);

            }catch (Exception e){
                e.printStackTrace();
            }
        }

        responseMap.put("errCode",errCode);
        responseMap.put("errMsg",errMsg);
        return responseMap;
    }
}
