package util

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)
type EASLoginInfo struct{
	UserName string `json:"userName"`
	Password string `json:"password"`
	SlnName	 string `json:"slnName"`
	DcName 	 string	`json:"dcName"`
	Language string	`json:"language"`
	DbType	 int32	`json:"dbType"`
}

var(
	LoginStr  = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:log="http://login.webservice.bos.kingdee.com">
   <soapenv:Header/>
   <soapenv:Body>
      <log:login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <userName xsi:type="xsd:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">userName?</userName>
         <password xsi:type="xsd:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">password?</password>
         <slnName xsi:type="xsd:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">slnName?</slnName>
         <dcName xsi:type="xsd:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">dcName?</dcName>
         <language xsi:type="xsd:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">language?</language>
         <dbType xsi:type="xsd:int">dbType?</dbType>
      </log:login>
   </soapenv:Body>
</soapenv:Envelope>
`
	LogoutStr = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:log="http://login.webservice.bos.kingdee.com">
   <soapenv:Header/>
   <soapenv:Body>
      <log:logout soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <userName xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">userName?</userName>
         <slnName xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">slnName?</slnName>
         <dcName xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">dcName?</dcName>
         <language xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">language?</language>
      </log:logout>
   </soapenv:Body>
</soapenv:Envelope>
`
	InsertPartsStr = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.synfacade.modernfarming.eas.kingdee.com">
    <soapenv:Header>
        <ns1:SessionId
            xmlns:ns1="http://login.webservice.bos.kingdee.com">SessionId?
        </ns1:SessionId>
    </soapenv:Header>
   <soapenv:Body>
      <web:synMaterial soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <request xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">strJson?</request>
      </web:synMaterial>
   </soapenv:Body>
</soapenv:Envelope>
`
	InsertPartsuselaidStr = `<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:app="http://app.ws.scm.eas.kingdee.com">
   <soapenv:Header>
        <ns1:SessionId
            xmlns:ns1="http://login.webservice.bos.kingdee.com">SessionId?
        </ns1:SessionId>
    </soapenv:Header>
   <soapenv:Body>
      <app:importBill soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
         <billType xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">billType?</billType>
         <billDataJSON xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">strJson?</billDataJSON>
         <billStatus xsi:type="xsd:int">1</billStatus>
      </app:importBill>
   </soapenv:Body>
</soapenv:Envelope>
`
)
func eastest(){
	sessionid := EASWebServiceLogin()
	//EASWebServicInsertParts(sessionid,"{}")
	EASWebServicInsertPartsuselaid(sessionid,"{}","007")

	//EASWebServiceLogout()
}
type Response struct {
	Body    rspBody  `xml:"Body" json:"body"`
}

type rspBody struct {
	Record []rqRecord `xml:"multiRef" json:"multiRef"`
	SynMaterialResponse SMReturn `xml:"synMaterialResponse" json:"SynMaterialResponse"`
	ImportBillResponse ImportBillResponse  `xml:"importBillResponse" json:"importBillResponse"`
}
type ImportBillResponse struct {
	ImportBillReturn string `xml:"importBillReturn" json:"importBillReturn"`
}

type SMReturn struct {
	SynMaterialReturn  string `xml:"synMaterialReturn" json:"synMaterialReturn"`
}
type rqRecord struct {
	SessionId  string `xml:"sessionId" json:"sessionId"`
}
func EASWebServiceLogin()string{
	client := &http.Client{}
	resstr := ReplaceStrWebSevice("login","user","kdeas@02","eas","MASM","L2","1","","","")
	body := bytes.NewBuffer([]byte(resstr))
	req, err := http.NewRequest("POST",
		"http://60.174.151.11:6888/ormrpc/services/EASLogin?wsdl",
		body,
	)
	req.Header.Set("Content-Type", "text/xml")
	req.Header.Set("SOAPAction", "application/soap+xml")
	if err != nil {
		// handle error
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	defer resp.Body.Close()
	result_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return ""
	}
	v := Response {}
	err = xml.Unmarshal([]byte(string(result_body)), &v)
	if err != nil {
		fmt.Println(err.Error())
	}
	if len(v.Body.Record)>0{
		fmt.Println(v.Body.Record[0].SessionId)
		return  v.Body.Record[0].SessionId
	}
	return ""
}
func EASWebServiceLogout(){
	client := &http.Client{}
	resstr := ReplaceStrWebSevice("logout","user","","eas","MASM","L2","","","","")
	body := bytes.NewBuffer([]byte(resstr))
	req, err := http.NewRequest("POST",
		"http://60.174.151.11:6888/ormrpc/services/EASLogin?wsdl",
		body,
	)
	req.Header.Set("Content-Type", "text/xml")
	req.Header.Set("SOAPAction", "application/soap+xml")
	if err != nil {
		// handle error
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}

	defer resp.Body.Close()

	result_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(string(result_body))
}

func EASWebServicInsertParts(SessionId,soapencJson string){
	client := &http.Client{}

	resstr := ReplaceStrWebSevice("InsertParts","","","","","","",SessionId,soapencJson,"")
	body := bytes.NewBuffer([]byte(resstr))

	req, err := http.NewRequest("POST",
		"http://60.174.151.11:6888/ormrpc/services/WSSynMasterDataFacade?wsdl",
		body,
	)
	req.Header.Set("Content-Type", "text/xml")
	req.Header.Set("SOAPAction", "application/soap+xml")
	if err != nil {
		// handle error
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	result_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	v := Response {}

	err = xml.Unmarshal([]byte(string(result_body)), &v)
	if err != nil {
		fmt.Println(err.Error())
	}
	resmap :=  make(map[string]string,0)
	err = json.Unmarshal([]byte(v.Body.SynMaterialResponse.SynMaterialReturn),&resmap)

	if resmap["success"] == "0"{
		fmt.Println(resmap["message"])
	}

	//fmt.Println(string(result_body))
}


func EASWebServicInsertPartsuselaid(SessionId,strJson,billType string){ //billType采购入库单:006 销售出库单:007 其他入库单:008 其他出库单:009 领料出库单:100 生产入库单:101
	client := &http.Client{}

	resstr := ReplaceStrWebSevice("InsertPartsuselaidStr","","","","","","",SessionId,strJson,billType)
	body := bytes.NewBuffer([]byte(resstr))

	req, err := http.NewRequest("POST",
		"http://60.174.151.11:6888/ormrpc/services/WSSCMWebServiceFacade?wsdl",
		body,
	)
	req.Header.Set("Content-Type", "text/xml")
	req.Header.Set("SOAPAction", "application/soap+xml")
	if err != nil {
		// handle error
	}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	result_body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	v := Response {}

	err = xml.Unmarshal([]byte(string(result_body)), &v)
	if err != nil {
		fmt.Println(err.Error())
	}
	resmap :=  make(map[string]interface{},0)
	if v.Body.ImportBillResponse.ImportBillReturn != "" {
		err = json.Unmarshal([]byte(v.Body.ImportBillResponse.ImportBillReturn),&resmap)

		fmt.Println(v.Body.ImportBillResponse.ImportBillReturn)
		fmt.Println(len(resmap["billErrors"].([]interface {})))
		if resmap["status"] == "2"{
			fmt.Println(resmap["msg"])
		}
	}

}

func ReplaceStrWebSevice(typeIn,userName,password,slnName,dcName,language,dbType,SessionId,strJson,billType string)string{
	res := ""
	switch typeIn {
	case "login":
		res = LoginStr
		res = strings.ReplaceAll(res,"userName?",userName)
		res = strings.ReplaceAll(res,"password?",password)
		res = strings.ReplaceAll(res,"slnName?",slnName)
		res = strings.ReplaceAll(res,"dcName?",dcName)
		res = strings.ReplaceAll(res,"language?",language)
		res = strings.ReplaceAll(res,"dbType?",dbType)
	case "logout":
		res = LogoutStr
		res = strings.ReplaceAll(res,"userName?",userName)
		res = strings.ReplaceAll(res,"slnName?",slnName)
		res = strings.ReplaceAll(res,"dcName?",dcName)
		res = strings.ReplaceAll(res,"language?",language)
	case "InsertParts":
		res = InsertPartsStr
		res = strings.ReplaceAll(res,"SessionId?",SessionId)
		res = strings.ReplaceAll(res,"strJson?",strJson)
	case "InsertPartsuselaidStr":
		res = InsertPartsuselaidStr
		res = strings.ReplaceAll(res,"SessionId?",SessionId)
		res = strings.ReplaceAll(res,"strJson?",strJson)
		res = strings.ReplaceAll(res,"billType?",billType)
	}
	return  res
}