package js

import (
	"encoding/json"
	"fmt"
	"gdyb/controllers"
	"gdyb/enums"
	"gdyb/service"
	"gdyb/utils"
	"github.com/astaxie/beego"
	"github.com/axgle/mahonia"
	"os"
	"regexp"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

type NmController struct {
	controllers.BaseAuthAPIController
}

func JSybRegistRouters() {
	beego.Router("/nmyb/1101", &NmController{}, "get:Post1101")
	beego.Router("/nmyb/2401", &NmController{}, "get:Post2401")
	beego.Router("/nmyb/2404", &NmController{}, "get:Post2404")
	beego.Router("/nmyb/2405", &NmController{}, "post:Post2405")
	beego.Router("/nmyb/2402", &NmController{}, "post:Post2402")
	beego.Router("/nmyb/2301", &NmController{}, "get:Post2301")
	beego.Router("/nmyb/2302", &NmController{}, "get:Post2302")
	beego.Router("/nmyb/2303", &NmController{}, "get:Post2303")
	beego.Router("/nmyb/2304", &NmController{}, "get:Post2304")
	beego.Router("/nmyb/2305", &NmController{}, "get:Post2305")
	beego.Router("/nmyb/2503", &NmController{}, "get:Get2503")
	beego.Router("/nmyb/readcard", &NmController{}, "get:ReadCard")
}

func (c *NmController) Post1101() {
	certNo := c.GetString("cert_no")
	org_name := c.GetString("org_name")
	doctor := c.GetString("doctor")
	fixmedins_code := c.GetString("fixmedins_code")
	insuplc_admdvs := c.GetString("insuplc_admdvs")
	mdtrtarea_admvs := c.GetString("mdtrtarea_admvs")
	secret_key := c.GetString("secret_key")
	id_card_type, _ := c.GetInt64("id_card_type")
	card_sn := c.GetString("card_sn")
	certificates := c.GetString("certificates")
	name := c.GetString("name")
	certificate, _ := strconv.ParseInt(certificates, 10, 64)
	service.ZHGdyb1101(certNo, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs, secret_key, id_card_type, card_sn, certificate, name)

}

func (c *NmController) Post2401() {

}

func (c *NmController) Post2404() {

}

func (c *NmController) Post2405() {

}

func (c *NmController) Post2402() {

}

func (c *NmController) Post2301() {

}

func (c *NmController) Post2303() {

}

func (c *NmController) Post2304() {

}

func (c *NmController) Post2305() {

}

func (c *NmController) Get2503() {

}

type ELeData struct {
	Data struct {
		SiNo            string `json:"si_no"`
		SiCardNo        string `json:"si_card_no"`
		SiCardIssueArea string `json:"si_card_issue_area"`
		Name            string `json:"name"`
		Gender          string `json:"gender"`
		IdType          string `json:"id_type"`
		IdNo            string `json:"id_no"`
		EcCardToken     string `json:"ecCardToken"`
	} `json:"data"`
	Code    int    `json:"code"`
	Message string `json:"message"`
}

func (c *NmController) ReadCard() {
	fixmedins_code := c.GetString("fixmedins_code")
	secret_key := c.GetString("secret_key")
	ak := c.GetString("ak")
	org_name := c.GetString("org_name")
	doctor := c.GetString("doctor")
	insuplc_admdvs := c.GetString("insuplc_admdvs")
	mdtrtarea_admvs := c.GetString("mdtrtarea_admvs")
	url := c.GetString("url")
	cainfo := c.GetString("cainfo")
	id_card_type := c.GetString("id_card_type")
	operator_id := c.GetString("operator_id")
	operator := c.GetString("operator")

	//result, request := service.Jsyb9001(org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs, secret_key, 1, url, cainfo, ak)
	//fmt.Println(request)
	//fmt.Println(result)

	c.TestGetBasBaseInit(fixmedins_code, secret_key, ak)
	fmt.Println(id_card_type)
	switch id_card_type {
	case "1":
		pCardInfo, pBusiCardInfo := c.GetBasBaseInfo()
		pBusiCardInfo = Remove0000(pBusiCardInfo)
		pCardInfo = Remove0000(pCardInfo)
		fmt.Println(":", ConvertToString(pCardInfo, "gbk", "utf-8"))

		fmt.Println(pBusiCardInfo)
		fmt.Println(pCardInfo)
		bas := strings.Split(pCardInfo, "|")
		basNumber := bas[2]
		id_card_no := bas[1]
		card_sn := bas[3]

		id_card_type_int, _ := strconv.ParseInt(id_card_type, 10, 64)

		if len(pCardInfo) > 0 && len(pBusiCardInfo) > 0 {
			result, _ := service.Jsyb1101A(basNumber, org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs, secret_key, id_card_type_int, card_sn, "1", url, ak, pBusiCardInfo, id_card_no, cainfo)
			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"status":         "0",
				"card_info":      pCardInfo,
				"busi_card_info": pBusiCardInfo,
				"result":         dat,
				"type":           "1",
			})
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"status": "-1",
			})

		}
		break
	case "3": //电子凭证
		_, pBusiCardInfo := c.GetELeInfo(fixmedins_code, operator_id, operator)
		//fmt.Println(pCardInfo)
		fmt.Println(pBusiCardInfo)
		pBusiCardInfo = Remove0000(pBusiCardInfo)
		//pCardInfo = Remove0000(pCardInfo)
		var ele ELeData
		err := json.Unmarshal([]byte(pBusiCardInfo), &ele)
		if err != nil {
			utils.ErrorLog("解析失败：%v", err)
		}
		token := ele.Data.EcCardToken
		if len(token) > 0 {
			result, _ := service.Jsyb1101B(org_name, doctor, fixmedins_code, insuplc_admdvs, mdtrtarea_admvs, secret_key, url, ak, token, cainfo, ele.Data.IdNo)
			var dat map[string]interface{}
			if err := json.Unmarshal([]byte(result), &dat); err == nil {
				fmt.Println(dat)
			} else {
				fmt.Println(err)
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"status": "0",
				//"card_info":      pCardInfo,
				"busi_card_info": pBusiCardInfo,
				"token":          token,
				"result":         dat,
				"type":           "2",
			})
		} else {
			c.ServeSuccessJSON(map[string]interface{}{
				"status": "-1",
			})

		}
		break

	}

}
func (c *NmController) TestGetBasBaseInit(code string, secret_key string, ak string) {
	DllDef := syscall.MustLoadDLL("HeaSecReadInfo.dll")
	Iinit := DllDef.MustFindProc("Init")
	//miConfig, _ := service.FindMedicalInsuranceInfo(c.GetAdminUserInfo().CurrentOrgId)
	str := make([]byte, 2048)
	inputData := make(map[string]interface{})
	inputData["IP"] = "10.72.3.87"
	inputData["PORT"] = "8086"
	inputData["TIMEOUT"] = "180"
	inputData["LOG_PATH"] = "C:\\log\\"
	//
	inputData["EC_URL"] = "http://10.72.3.127:10086/localcfc/api/hsecfc/localQrCodeQuery"
	inputData["CARD_PASSTYPE"] = "1"
	inputData["API_NAME"] = "hssServives"
	inputData["API_VERSION"] = "1.0.0"
	inputData["ACCESS_KEY"] = ak

	inputData["SECRETKEY"] = secret_key
	inputData["ORG_ID"] = code
	inputData["EXT"] = ""
	bytesData, _ := json.Marshal(inputData)
	fmt.Println(inputData)
	fmt.Println(bytesData)

	ret, _, err := Iinit.Call((uintptr)(unsafe.Pointer(&bytesData[0])), (uintptr)(unsafe.Pointer(&str[0])))
	if ret != 0 {
		fmt.Println("SSCard的报错原因:", err)
		fmt.Println("SSCard的运算结果为:", ret)
		fmt.Println("SSCard的返回结果为:", string(str))
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeReadCardException)
		return
	}
	fmt.Println("SSCard的返回结果为:", string(str))

	result := int(ret)
	fmt.Println("SSCard的运算结果为1:", result)
	//initFlag = 1
	return
}
func (c *NmController) GetBasBaseInfo() (string, string) {
	DllDef := syscall.MustLoadDLL("HeaSecReadInfo.dll")
	readCard := DllDef.MustFindProc("ReadCardBas")
	fmt.Println(readCard)
	fmt.Println("!!!!!")
	pCardInfo := make([]byte, 2048)
	pBusiCardInfo := make([]byte, 8192)
	ret2, _, _ := readCard.Call((uintptr)(unsafe.Pointer(&pCardInfo[0])), (uintptr)(unsafe.Pointer(&pBusiCardInfo[0])))
	fmt.Println(ret2)
	fmt.Println(DeleteExtraSpace(string(pCardInfo)))
	fmt.Println(DeleteExtraSpace(string(pBusiCardInfo)))
	fmt.Println(":", ConvertToString(DeleteExtraSpace(string(pCardInfo)), "gbk", "utf-8"))
	fmt.Println(":", ConvertToString(DeleteExtraSpace(string(pBusiCardInfo)), "gbk", "utf-8"))
	if ret2 != 0 {
		return "", ""
	}
	return DeleteExtraSpace(string(pCardInfo)), DeleteExtraSpace(string(pBusiCardInfo))
}
func (c *NmController) GetELeInfo(code string, operator_id string, operator_name string) (string, string) {
	DllDef := syscall.MustLoadDLL("HeaSecReadInfo.dll")
	readCard := DllDef.MustFindProc("EcCardQuery")
	fmt.Println(readCard)
	fmt.Println("!!!!!")
	//pCardInfo := make([]byte, 8192)
	pBusiCardInfo := make([]byte, 8192)

	//data := make(map[string]interface{})
	//pData := make(map[string]interface{})

	//inputData := make(map[string]interface{})
	//inputData["orgId"] = code
	//inputData["businessType"] = "01101"
	//inputData["operatorId"] = operator_id
	//inputData["operatorName"] = operator_name
	//inputData["officeId"] = "001"
	//inputData["officeName"] = "血透室"

	//data["data"] = inputData
	//data["transType"] = "ec.query"
	//data["orgId"] = code
	//bytesData, _ := json.Marshal(data)
	//pCardInfo = bytesData
	ret2, _, _ := readCard.Call((uintptr)(unsafe.Pointer(&pBusiCardInfo[0])))
	fmt.Println(ret2)
	//fmt.Println(DeleteExtraSpace(string(bytesData)))
	fmt.Println(DeleteExtraSpace(string(pBusiCardInfo)))
	//fmt.Println(":", ConvertToString(DeleteExtraSpace(string(bytesData)), "gbk", "utf-8"))
	fmt.Println(":", ConvertToString(DeleteExtraSpace(string(pBusiCardInfo)), "gbk", "utf-8"))
	if ret2 != 0 {
		return "", ""
	}
	return DeleteExtraSpace(""), DeleteExtraSpace(string(pBusiCardInfo))
}
func IntPtr(n int) uintptr {
	return uintptr(n)
}
func StrPtr(s string) uintptr {
	return uintptr(unsafe.Pointer(syscall.StringBytePtr(s)))
}

type Charset string

const (
	UTF8    = Charset("UTF-8")
	GB18030 = Charset("GB18030")
)

func ConvertToString(src string, srcCode string, tagCode string) string {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(tagCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)
	result := string(cdata)
	return result
}
func DeleteExtraSpace(s string) string {
	//删除字符串中的多余空格，有多个空格时，仅保留一个空格
	s1 := strings.Replace(s, "  ", " ", -1)      //替换tab为空格
	regstr := "\\s{2,}"                          //两个及两个以上空格的正则表达式
	reg, _ := regexp.Compile(regstr)             //编译正则表达式
	s2 := make([]byte, len(s1))                  //定义字符数组切片
	copy(s2, s1)                                 //将字符串复制到切片
	spc_index := reg.FindStringIndex(string(s2)) //在字符串中搜索
	for len(spc_index) > 0 {                     //找到适配项
		s2 = append(s2[:spc_index[0]+1], s2[spc_index[1]:]...) //删除多余空格
		spc_index = reg.FindStringIndex(string(s2))            //继续在字符串中搜索
	}
	return string(s2)
}
func Remove0000(s string) string {
	str := make([]rune, 0, len(s))
	for _, v := range []rune(s) {
		if v == 0 {
			continue
		}
		str = append(str, v)
	}
	return string(str)
}
func saveJsLog(result string, request string, infno string, desc string, org_name string) {

	//org_id, _ := beego.AppConfig.Int64("org_id")
	//miConfig, _ := service.FindMedicalInsuranceInfo(org_id)
	dir := org_name + "日志"
	utils.Mkdir(dir)
	month := time.Unix(1557042972, 0).Format("1")
	year := time.Now().Format("2006")
	month = time.Now().Format("01")
	day := time.Now().Format("02")
	hour := time.Now().Format("15")
	min := time.Now().Format("04")
	sec := time.Now().Format("05")

	result_time := year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec

	file := org_name + "_" + year + month + day + "_log"
	file_name := file + ".txt"
	file_path := org_name + "日志" + "/" + file_name
	exist, _ := utils.PathExists(file_path)
	if exist { //存在
		fmt.Println("存在")
		f, err := os.OpenFile(file_path, os.O_WRONLY, 0644)
		if err != nil {
			fmt.Println("read fail")
		}
		content := "\r\n" + "\r\n" + "\r\n" + result_time + " " + "【 " + desc + infno + "入参" + " 】：" + "\r\n" + request + "\r\n" + result_time + " " + "【 " + desc + infno + "出参" + " 】：" + "\r\n" + result
		n, _ := f.Seek(0, 2)
		_, err = f.WriteAt([]byte(content), n)

	} else { //不存在
		fmt.Println("文件不存在，创建文件")
		f, err := os.Create(org_name + "日志" + "/" + file_name)
		defer f.Close()
		if err != nil {
		} else {
			_, err = f.Write([]byte("记录日志"))
		}
	}

}
