package com.jojubanking.boot.module.system.job;

import com.jojubanking.boot.framework.common.util.http.SoapUtil;
import com.jojubanking.boot.framework.common.util.xml.XmlUtil;
import com.jojubanking.boot.framework.quartz.core.handler.JobHandler;
import com.jojubanking.boot.module.system.service.ksinfo.KsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GetKsinfoDaily implements JobHandler {

    @Resource
    private KsInfoService ksInfoService;


    @Override
    public String execute(String param) throws Exception {
        //从his获取科室列表
        String xml = queryAppointDeptMark();
        // 解析报文

        List<Map<String, Object>> lst = XmlUtil.getPacsRes(xml, "MOP_OutpRegisterDeptQuery");

        //根据科室列表更新或者插入ks表
        for(int    i=0;    i<lst.size(); i++){
            Map<String, Object> ks = lst.get(i);
            String KsCode = ks.get("DepartCode").toString();
            String Name = ks.get("DepartName").toString();
            String Departtype = ks.get("DepartType").toString();
            ksInfoService.updateKsInfoPerDay(KsCode, Name, Departtype);
        }

        return String.format("刷新科室列表");
    }

    /**
     * 部门查询
     *
     * @param
     * @return
     */
    public String queryAppointDeptMark() throws Exception {
        StringBuffer str = new StringBuffer();
        str.append("<SearchType>");
        str.append("1");
        str.append("</SearchType>");
        str.append("<DepartCode>");
        str.append("");
        str.append("</DepartCode>");
        str.append("<DepartLevel>");
        str.append("");
        str.append("</DepartLevel>");
        str.append("<DepartType>");
        str.append("0");
        str.append("</DepartType>");
//<QueryCode>420621199809253859</QueryCode>

        String reqXml = requestXml("MOP_OutpRegisterDeptQuery", str.toString());
        String respXml = SoapUtil.soapMethod(reqXml);
        log.info("MOP_OutpRegisterDeptQuery:" + reqXml);
        log.info("MOP_OutpRegisterDeptQuery:" + respXml);
        return respXml;
    }
    public static String requestXml(String method, String xml) {
        StringBuffer str = new StringBuffer();
        str.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">");
        str.append("<soapenv:Header/>");
        str.append("<soapenv:Body>");
        str.append("<tem:" + method);
        str.append("><tem:InMsg>");
        str.append("<![CDATA[");
        str.append("<request>");
        str.append(xml);
        str.append("</request>");
        str.append("]]>");
        str.append("</tem:InMsg>");
        str.append("</tem:" + method);
        str.append("></soapenv:Body>");
        str.append("</soapenv:Envelope>");
        return str.toString();
    }

}
