package com.yihu.jw.hospital.prescription.service;

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import jxl.WorkbookSettings;
import jxl.write.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PayInfoNoticeService {
    @Value("${hospital.url}")
    private String serverUrl;
    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private BasePatientDao patientDao;
    @Autowired
    private HibenateUtils hibenateUtils;

    @Value("${wechat.id}")
    private String wxId;


    @Value("${wechat.flag}")
    private boolean flag;

    public String pushPrescriptionPay(String patient,String doctorName,String orderNo,String outpatientId,String prescriptionId,String total,String title,String url){
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO!=null){
            String userName = patientDO.getName();
            String idcard = patientDO.getIdcard();
            String phone = patientDO.getMobile();
            if (!StringUtils.isNotBlank(url)){
                url = "https://hlwyy.xmzsh.com/ims-wx/index.html#/returnVisit/prescriptionDetail?outpatientId="+outpatientId+"&id="+prescriptionId;
            }
            String remark = "结算方式：微信结算" +
                    "点击查看取药\n物流信息";
            return paySuccessNotice(userName,idcard,phone,title,url,doctorName,total,"0",total,orderNo,remark);

        }
        return null;
    }

    public String pushPrescriptionPayAndHsjc(String patient,String doctorName,String orderNo,String id,String total,String title,String url,String realOrder){
        BasePatientDO patientDO = patientDao.findById(patient);
        if (patientDO!=null){
            String userName = patientDO.getName();
            String idcard = patientDO.getIdcard();
            String phone = patientDO.getMobile();
            if (!StringUtils.isNotBlank(url)){
                url = "https://hlwyy.xmzsh.com/hlwyy/ims-wx/#/nucleicTest/detail?id="+id;
            }
            String remark = "结算方式：微信结算 \r\n" +
                    "发票流水号："+realOrder+"\r\n"+
                    "点击查看核酸预约开单信息";
            return paySuccessNotice(userName,idcard,phone,title,url,doctorName,total,"0",total,orderNo,remark);

        }
        return null;
    }


    /**
     * 支付成功提醒
     * @param userName 用户名 （不能为空）
     * @param idCard 身份证 （能为空）
     * @param phone 推送人手机号 （不能为空）
     * @param title 推送标题 （不能为空）
     * @param url 支付链接   （不能为空）
     * @param doctorName 就诊医生 （不能为空）
     * @param total 总费用 （不能为空）
     * @param miPay 医保支付 （不能为空）
     * @param selfPay 个人支付 （不能为空）
     * @param orderNo 单据号 （不能为空）
     * @param remark 备注 （不能为空）
     * @return
     * @throws Exception
     */
    public String paySuccessNotice(String userName,String idCard,String phone,String title,String url,
                                   String doctorName,String total,String miPay,String selfPay,String orderNo,String remark) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName", userName);
        jsonObject.put("idCard", idCard);
        jsonObject.put("phone", phone);
        jsonObject.put("title", title);
        jsonObject.put("url", url);
        jsonObject.put("doctorName", doctorName);
        jsonObject.put("total", total);
        jsonObject.put("miPay", miPay);
        jsonObject.put("selfPay", selfPay);
        jsonObject.put("orderNo", orderNo);
        jsonObject.put("remark", remark);
        String responseMsg = httpClientUtil.sendPost(serverUrl + "/interface/paySuccessNoticePush.htm", jsonObject.toJSONString());
        JSONObject result = new JSONObject();
        String respCode = "";
        if (responseMsg != null) {
            result = JSONObject.parseObject(responseMsg);
            respCode = result.get("respCode").toString();
        }
        return respCode;
    }

    //导出es查询数据
    public void exportEsPrescription(OutputStream os, List<Map<String,Object>> totallist,List<Map<String,Object>> listDay) throws Exception{

        WorkbookSettings settings = new WorkbookSettings();
        settings.setWriteAccess(null);
        settings.setEncoding("UTF-8");
        WritableWorkbook wwb = jxl.Workbook.createWorkbook(os,settings);
        try {
            WritableSheet ws;
            ws = wwb.createSheet("sheet", 1);
            WritableSheet ws2 = wwb.createSheet("sheet2", 2);
            String[] header = {"医生姓名", "出诊科室","发起问诊", "接诊数量", "开方数量", "物流数量"};
            String[] header2 = {"时间", "发起问诊", "接诊数量", "开方数量", "物流数量"};
        int k = 0;
        int m =0;
            for (String h : header) {
                addCell(ws, 0, k, h);//表名，行，列，header
                k++;
            }
            for (String h : header2) {
                addCell(ws2, 0, m, h);//表名，行，列，header
                m++;
            }
            int i = 1;
            if (null!=totallist&&totallist.size()>0){
                for (int n=0;n<totallist.size();n++) {
                    Map<String,Object> object = totallist.get(n);
                    addCell(ws, i, 0, object.get("doctorName").toString(), "");
                    addCell(ws, i, 1, null==object.get("deptName")?"":object.get("deptName").toString(),"");
                    addCell(ws, i, 2, null==object.get("total")?"":object.get("total").toString(),"");
                    addCell(ws, i, 3, null==object.get("pickNum")?"":object.get("pickNum").toString(),"");
                    addCell(ws, i, 4, null==object.get("preNum")?"":object.get("preNum").toString(),"");
                    addCell(ws, i, 5, null==object.get("wlNum")?"":object.get("wlNum").toString(),"");
                    i++;
                }
            }
            int j =1;
            if (null!=listDay&&listDay.size()>0){
                for (int n=0;n<listDay.size();n++){
                    Map<String,Object> object = listDay.get(n);
                    addCell(ws2, j, 0, object.get("daliy").toString(), "");
                    addCell(ws2, j, 1, null==object.get("total")?"":object.get("total").toString(),"");
                    addCell(ws2, j, 2, null==object.get("pickNum")?"":object.get("pickNum").toString(),"");
                    addCell(ws2, j, 3, null==object.get("preNum")?"":object.get("preNum").toString(),"");
                    addCell(ws2, j, 4, null==object.get("wlNum")?"":object.get("wlNum").toString(),"");
                    j++;
                }
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
            if (wwb != null) wwb.close();
            throw e;
        }
    }
    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data) throws WriteException {
        Label label = new Label(column, row, data);
        ws.addCell(label);
    }

    //添加单元格内容
    public void addCell(WritableSheet ws, int row, int column, String data, String memo) throws WriteException {
        Label label = new Label(column, row, data);
        if (!org.springframework.util.StringUtils.isEmpty(memo)) {
            WritableCellFeatures cellFeatures = new WritableCellFeatures();
            cellFeatures.setComment(memo);
            label.setCellFeatures(cellFeatures);
        }
        ws.addCell(label);
    }
    public List<Map<String,Object>> dealSqlQuery(String beginTime,String endTime){
        //发起问诊量
        String sqlOutPatient="SELECT\n" +
                "\tt.doctor as \"doctor\",\n" +
                "\tt.doctor_name as \"doctorName\",\n" +
                "\tt.dept_name as \"deptName\",\n" +
                "\tcount(*) as \"total\" \n" +
                "FROM\n" +
                "\t wlyy_outpatient t \n" +
                "WHERE 1=1 and t.doctor is not null\n " +
                " AND t.doctor!='402803816babc778016babd0dee21112'" ;
        //接诊量
        String sqlDoctorOut = "SELECT\n" +
                "\tt.doctor as \"doctor\",\n" +
                "\tt.doctor_name as \"doctorName\",\n" +
                "\tt.dept_name as \"deptName\",\n" +
                "\tcount(*) as \"total\" \n" +
                "FROM\n" +
                "\t wlyy_outpatient t \n" +
                "WHERE 1=1 and t.doctor is not null\n" +
                " AND t.doctor!='402803816babc778016babd0dee21112'";
        //开具处方量
        String sqlPrescription = "SELECT\n" +
                "\tt.doctor as \"doctor\",\n" +
                "\tt.doctor_name as \"doctorName\",\n" +
                "\tt.dept_name as \"deptName\",\n" +
                "\tcount(*) as \"total\" \n" +
                "FROM\n" +
                "\t wlyy_prescription t \n" +
                "WHERE 1=1 and t.doctor is not null\n" +
                " AND t.doctor!='402803816babc778016babd0dee21112'" ;
        //物流量
        String sqlWL = "SELECT\n" +
                "\to.doctor as \"doctor\",\n" +
                " o.doctor_name as \"doctorName\",\n" +
                " o.dept_name as \"deptName\",\n" +
                " count(*) as \"total\"" +
                "FROM\n" +
                " base.wlyy_prescription_expressage t\n" +
                "LEFT JOIN base.wlyy_prescription b ON b.outpatient_id = t.outpatient_id\n" +
                "LEFT JOIN base.wlyy_outpatient o ON o.id= b.outpatient_id\n" +
                "WHERE 1=1 and o.doctor is not null\n" +
                " AND o.doctor!='402803816babc778016babd0dee21112'" ;
        if (StringUtils.isNotEmpty(beginTime)){
            wxId="xx";
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sqlOutPatient+=" and t.create_time > '" + beginTime + " 00:00:00' ";
                    sqlDoctorOut+=" and t.create_time > '" + beginTime + " 00:00:00' ";
                    sqlPrescription+=" and t.create_time > '" + beginTime + " 00:00:00' ";
                    sqlWL+=" and t.create_time > '" + beginTime + " 00:00:00' ";

                }else {
                    sqlOutPatient+=" and t.create_time > to_date('" + beginTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
                    sqlDoctorOut+=" and t.create_time > to_date('" + beginTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
                    sqlPrescription+=" and t.create_time > to_date('" + beginTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";
                    sqlWL+=" and t.create_time > to_date('" + beginTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";

                }
            }else{
                sqlOutPatient+=" and t.create_time > '" + beginTime + " 00:00:00'";
                sqlDoctorOut+=" and t.create_time > '" + beginTime + " 00:00:00'";
                sqlPrescription+=" and t.create_time > '" + beginTime + " 00:00:00'";
                sqlWL+=" and t.create_time > '" + beginTime + " 00:00:00'";
            }
        }
        if (StringUtils.isNotEmpty(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    sqlOutPatient+="  and t.create_time<'" + endTime + " 23:59:59'";
                    sqlDoctorOut+="  and t.create_time<'" + endTime + " 23:59:59'";
                    sqlPrescription+="  and t.create_time<'" + endTime + " 23:59:59'";
                    sqlWL+="  and t.create_time<'" + endTime + " 23:59:59'";

                }else {
                    sqlOutPatient+="  and t.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                    sqlDoctorOut+="  and t.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                    sqlPrescription+="  and t.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                    sqlWL+="  and t.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
            }else{
                sqlOutPatient+="  and t.create_time<'" + endTime + " 23:59:59'";
                sqlDoctorOut+="  and t.create_time<'" + endTime + " 23:59:59'";
                sqlPrescription+="  and t.create_time<'" + endTime + " 23:59:59'";
                sqlWL+="  and t.create_time<'" + endTime + " 23:59:59'";
            }
        }
        sqlOutPatient+="\tAND t.patient_name NOT IN ( '王志南', '游水连', '林志芳', '郑绩', '陈晓亮', '王培坤' ) \n" +
                "\tAND t.STATUS IN ( 0,1,2,3 )\n" +
                "\tGROUP BY t.doctor_name,\n" +
                "\tt.dept_name,t.doctor";
        sqlDoctorOut+= "\tAND t.patient_name NOT IN ( '王志南', '游水连', '林志芳', '郑绩', '陈晓亮', '王培坤' ) \n" +
                "\tAND t.STATUS IN ( 1, 2, 3 )\n" +
                " and t.pay_status =1 "+
                "\tGROUP BY t.doctor_name,\n" +
                "\tt.dept_name ,t.doctor";
        sqlPrescription+="\tAND t.patient_name NOT IN ( '王志南', '游水连', '林志芳', '郑绩', '陈晓亮', '王培坤' ) \n" +
                "\tGROUP BY t.doctor_name,\n" +
                "\tt.dept_name,t.doctor";
        sqlWL+= "AND t. NAME NOT IN (\n" +
                " '王志南',\n" +
                " '游水连',\n" +
                " '林志芳',\n" +
                " '郑绩',\n" +
                " '陈晓亮',\n" +
                " '王培坤',\n" +
                " '林'\n" +
                ")\n" +
                "AND t.oneself_pickup_flg = 0\n" +
                "\n" +
                "AND b.`status`IN(20,32,100)\n" +
                "AND b.drug_fee !=0\n" +
                "AND b.real_order IS not NULL"+
                "\tGROUP BY o.doctor_name,\n" +
                "\to.dept_name,o.doctor";
        List<Map<String,Object>> result = new ArrayList<>();
        List<Map<String,Object>> outPatient=hibenateUtils.createSQLQuery(sqlOutPatient);
        List<Map<String,Object>> docPickup=hibenateUtils.createSQLQuery(sqlDoctorOut);
        List<Map<String,Object>> prescription=hibenateUtils.createSQLQuery(sqlPrescription);
        List<Map<String,Object>> wl=hibenateUtils.createSQLQuery(sqlWL);
        if(null!=outPatient&&outPatient.size()>0){
            for (Map<String,Object> map:outPatient){
                if (docPickup!=null&&docPickup.size()>0){
                    for (Map<String,Object> pickMap:docPickup){
                        if (pickMap.get("doctor").toString().equalsIgnoreCase(map.get("doctor").toString())){
                            map.put("pickNum",null==pickMap.get("total")?"":pickMap.get("total").toString());
                        }
                    }
                }
                if (prescription!=null&&prescription.size()>0){
                    for (Map<String,Object> pre:prescription){
                        if (pre.get("doctor").toString().equalsIgnoreCase(map.get("doctor").toString())){
                            map.put("preNum",null==pre.get("total")?"":pre.get("total").toString());
                        }
                    }
                }
                if (wl!=null&&wl.size()>0){
                    for (Map<String,Object> wMap:wl){
                        if (wMap.get("doctor").toString().equalsIgnoreCase(map.get("doctor").toString())){
                            map.put("wlNum",null==wMap.get("total")?"":wMap.get("total").toString());
                        }
                    }
                }
                result.add(map);
            }
        }
     return result;
    }
    //按天分组查询
    public List<Map<String,Object>> dealSqlQueryGroupDay(String beginTime,String endTime){

        String sqlDemo = "SELECT\n" +
                "\tdate_format( t.create_time, '%Y-%m-%d' ) as \"daliy\",\n" +
                "\tcount( * ) as \"total\" \n" +
                "FROM\n" ;
        //发起复诊量
        String outPatinet =sqlDemo+ "\twlyy_outpatient t where 1=1 AND t.doctor!='402803816babc778016babd0dee21112' and " +
                "t.STATUS IN ( 0,1,2,3 )";
        //接诊
        String outPick  =sqlDemo+  "\twlyy_outpatient t where 1=1 AND t.doctor!='402803816babc778016babd0dee21112' " +
                " and t.STATUS IN (1,2,3) and t.doctor is not null ";
        //处方
        String pre = sqlDemo+"\twlyy_prescription t where 1=1 AND t.doctor!='402803816babc778016babd0dee21112'";
        //物流
        String wl =sqlDemo+" base.wlyy_prescription_expressage t\n" +
                "LEFT JOIN base.wlyy_prescription b ON b.outpatient_id = t.outpatient_id\n" +
                "LEFT JOIN base.wlyy_outpatient o ON o.id= b.outpatient_id\n" +
                "WHERE t.oneself_pickup_flg = 0\n" +
                "AND b.`status`IN(20,32,100)\n" +
                "AND b.drug_fee !=0\n" +
                "AND b.real_order IS not NULL" +
                " AND o.doctor!='402803816babc778016babd0dee21112'";
        String deltime = "";
        if (StringUtils.isNotEmpty(beginTime)){
            wxId="xx";
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    deltime+=" and t.create_time > '" + beginTime + " 00:00:00' ";

                }else {
                    deltime+=" and t.create_time > to_date('" + beginTime + " 00:00:00', 'yyyy-mm-dd hh24:mi:ss') ";

                }
            }else{
                deltime+=" and t.create_time > '" + beginTime + " 00:00:00'";
            }
        }
        if (StringUtils.isNotEmpty(endTime)){
            if("xm_ykyy_wx".equals(wxId)){
                if (flag){
                    deltime+="  and t.create_time<'" + endTime + " 23:59:59'";

                }else {
                    deltime+="  and t.create_time< to_date('" + endTime + " 23:59:59','yyyy-mm-dd hh24:mi:ss')";
                }
            }else{
                deltime+="  and t.create_time<'" + endTime + " 23:59:59'";
            }
        }
        deltime+=" group by date_format(t.create_time, '%Y-%m-%d');";
        outPatinet+=deltime;
        outPick +=deltime;
        pre +=deltime;
        wl+=deltime;
        List<Map<String,Object>> result = new ArrayList<>();
        List<Map<String,Object>> outPatient=hibenateUtils.createSQLQuery(outPatinet);
        List<Map<String,Object>> docPickup=hibenateUtils.createSQLQuery(outPick);
        List<Map<String,Object>> prescription=hibenateUtils.createSQLQuery(pre);
        List<Map<String,Object>> wls=hibenateUtils.createSQLQuery(wl);
        if(null!=outPatient&&outPatient.size()>0){
            for (Map<String,Object> map:outPatient){
                if (docPickup!=null&&docPickup.size()>0){
                    for (Map<String,Object> pickMap:docPickup){
                        if (pickMap.get("daliy").toString().equalsIgnoreCase(map.get("daliy").toString())){
                            map.put("pickNum",null==pickMap.get("total")?"":pickMap.get("total").toString());
                        }
                    }
                }
                if (prescription!=null&&prescription.size()>0){
                    for (Map<String,Object> preMap:prescription){
                        if (preMap.get("daliy").toString().equalsIgnoreCase(map.get("daliy").toString())){
                            map.put("preNum",null==preMap.get("total")?"":preMap.get("total").toString());
                        }
                    }
                }
                if (wl!=null&&wls.size()>0){
                    for (Map<String,Object> wMap:wls){
                        if (wMap.get("daliy").toString().equalsIgnoreCase(map.get("daliy").toString())){
                            map.put("wlNum",null==wMap.get("total")?"":wMap.get("total").toString());
                        }
                    }
                }
                result.add(map);
            }
        }
        return result;
    }
}

