package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"gdyb/models"
	"github.com/jinzhu/gorm"
	"io/ioutil"
	"net/http"
	"time"
)

func UpdateHisPatientStatusTwo(his *models.VMHisPatient) {
	writeDb.Save(&his)
}

func GetUnSettleHisPrescriptionFiveTen(org_id int64, patient_id int64, record_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject").Preload("GoodInfo", "status=1").Preload("XtHisProjectTeam", "status = 1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND order_status <> 3 and order_status <> 5  AND p_type = ?", org_id, record_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetUnSettleMonthHisPrescription(org_id int64, patient_id int64, start_date int64, end_date int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject").Preload("GoodInfo", "status=1").Preload("XtHisProjectTeam", "status = 1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND order_status <> 5 AND p_type <> 1", org_id, start_date, end_date, patient_id).
		Find(&prescription).Error
	return
}

func GetHisOrderFour(patient_id string, infoSeq string, docId string) (order models.HisOrder, err error) {
	if len(docId) > 0 {
		err = readDb.Model(&models.HisOrder{}).Where("mdtrt_id = ? AND psn_no = ? AND setl_id = ? AND status = 1", infoSeq, patient_id, docId).First(&order).Error
	} else {
		err = readDb.Model(&models.HisOrder{}).Where("mdtrt_id = ? AND psn_no = ? AND status = 1 ", infoSeq, patient_id).First(&order).Error
	}
	return
}

func GetHisPatientForCoordinate(id_card_no string) (string, string) {

	//input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputData["idcard"] = id_card_no // 就诊凭证编号

	var inputLog string
	bytesData, err := json.Marshal(inputData)
	inputLog = string(bytesData)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	var url string
	gdyb_url := "http://218.104.146.179:9091/esb/listener/getPatientType"
	url = gdyb_url

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("GET", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("code", "Xmrjyy")

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	return str, inputLog

}
func UploadPrescriptionForCoordinate(info models.UploadInfo) (string, string) {

	//input := make(map[string]interface{})
	inputData := make(map[string]interface{})

	diags := make([]map[string]interface{}, 0)
	//diags := make([]map[string]interface{}, 0)

	presInfos := make([]map[string]interface{}, 0)

	for _, item := range info.Diag {
		inputDataDiag := make(map[string]interface{})
		inputDataDiag["vao06"] = item.Vao06
		inputDataDiag["bak02"] = item.Bak02
		diags = append(diags, inputDataDiag)
	}

	for _, item := range info.PresInfo {
		inputDataPresInfo := make(map[string]interface{})
		inputDataPresInfo["cbm06"] = item.Cbm06
		inputDataPresInfo["cbm07"] = item.Cbm07
		inputDataPresInfo["cbmid"] = item.Cbmid
		presDetails := make([]map[string]interface{}, 0)

		for _, subItem := range item.PresDetail {
			inputDataPresDetail := make(map[string]interface{})
			inputDataPresDetail["vaf59"] = subItem.Vaf59
			Items := make([]map[string]interface{}, 0)
			for _, subSubItem := range subItem.Item {
				inputDataItem := make(map[string]interface{})
				inputDataItem["bbx01"] = subSubItem.Bbx01
				inputDataItem["bda01"] = subSubItem.Bda01
				inputDataItem["bby01"] = subSubItem.Bby01
				inputDataItem["bck01b"] = subSubItem.Bck01b
				inputDataItem["bck01d"] = subSubItem.Bck01d
				inputDataItem["bdi01"] = subSubItem.Bdi01
				inputDataItem["rownr"] = subSubItem.Rownr
				inputDataItem["vaf11"] = subSubItem.Vaf11
				inputDataItem["vaf14"] = subSubItem.Vaf14
				inputDataItem["vaf15"] = subSubItem.Vaf15
				inputDataItem["vaf17"] = subSubItem.Vaf17
				inputDataItem["vaf18"] = subSubItem.Vaf18
				inputDataItem["vaf19"] = subSubItem.Vaf19
				inputDataItem["vaf20"] = subSubItem.Vaf20
				inputDataItem["vaf21"] = subSubItem.Vaf21
				inputDataItem["vaf22"] = subSubItem.Vaf22
				inputDataItem["vaf32"] = subSubItem.Vaf32
				inputDataItem["vaf35"] = subSubItem.Vaf35
				inputDataItem["vaf36"] = subSubItem.Vaf36
				inputDataItem["vaf58"] = subSubItem.Vaf58
				inputDataItem["vaf61"] = subSubItem.Vaf61
				Items = append(Items, inputDataItem)

			}
			inputDataPresDetail["item"] = Items
			presDetails = append(presDetails, inputDataPresDetail)
		}
		inputDataPresInfo["presDetail"] = presDetails
		presInfos = append(presInfos, inputDataPresInfo)
	}

	inputData["vaa01"] = info.Vaa01   // 就诊凭证编号
	inputData["Fasong"] = info.Fasong // 就诊凭证编号
	inputData["vaa07"] = info.Vaa07   // 就诊凭证编号
	inputData["bck01c"] = info.Bck01c // 就诊凭证编号
	inputData["bce02a"] = "1001"      // 就诊凭证编号

	inputData["diag"] = diags         // 就诊凭证编号
	inputData["presInfo"] = presInfos // 就诊凭证编号

	var inputLog string
	bytesData, err := json.Marshal(inputData)
	inputLog = string(bytesData)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	var url string
	gdyb_url := "http://218.104.146.179:9091/esb/listener/sendPretreat"
	url = gdyb_url

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("code", "Xmrjyy")

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	return str, inputLog

}

func UploadPrescriptionForCoordinateHospital(info models.UploadInfo) (string, string) {

	//input := make(map[string]interface{})
	inputData := make(map[string]interface{})

	diags := make([]map[string]interface{}, 0)
	//diags := make([]map[string]interface{}, 0)

	presInfos := make([]map[string]interface{}, 0)

	for _, item := range info.Diag {
		inputDataDiag := make(map[string]interface{})
		inputDataDiag["vao06"] = item.Vao06
		inputDataDiag["bak02"] = item.Bak02
		diags = append(diags, inputDataDiag)
	}

	for _, item := range info.PresInfo {
		inputDataPresInfo := make(map[string]interface{})
		inputDataPresInfo["cbm06"] = item.Cbm06
		inputDataPresInfo["cbm07"] = item.Cbm06
		inputDataPresInfo["cbmid"] = item.Cbmid
		presDetails := make([]map[string]interface{}, 0)

		for _, subItem := range item.PresDetail {
			inputDataPresDetail := make(map[string]interface{})
			inputDataPresDetail["vaf59"] = subItem.Vaf59
			Items := make([]map[string]interface{}, 0)
			for _, subSubItem := range subItem.Item {
				inputDataItem := make(map[string]interface{})
				inputDataItem["bbx01"] = subSubItem.Bbx01
				inputDataItem["bda01"] = subSubItem.Bda01
				inputDataItem["bby01"] = subSubItem.Bby01
				inputDataItem["bck01b"] = subSubItem.Bck01b
				inputDataItem["bck01d"] = subSubItem.Bck01d
				inputDataItem["bdi01"] = subSubItem.Bdi01
				inputDataItem["rownr"] = subSubItem.Rownr
				inputDataItem["vaf11"] = subSubItem.Vaf11
				inputDataItem["vaf14"] = subSubItem.Vaf14
				inputDataItem["vaf15"] = subSubItem.Vaf15
				inputDataItem["vaf17"] = subSubItem.Vaf17
				inputDataItem["vaf18"] = subSubItem.Vaf18
				inputDataItem["vaf19"] = subSubItem.Vaf19
				inputDataItem["vaf20"] = subSubItem.Vaf20
				inputDataItem["vaf21"] = subSubItem.Vaf21
				inputDataItem["vaf22"] = subSubItem.Vaf22
				inputDataItem["vaf32"] = subSubItem.Vaf32
				inputDataItem["vaf35"] = subSubItem.Vaf35
				inputDataItem["vaf36"] = subSubItem.Vaf36
				inputDataItem["vaf58"] = subSubItem.Vaf58
				inputDataItem["vaf61"] = subSubItem.Vaf61
				Items = append(Items, inputDataItem)

			}
			inputDataPresDetail["item"] = Items
			presDetails = append(presDetails, inputDataPresDetail)
		}
		inputDataPresInfo["presDetail"] = presDetails
		presInfos = append(presInfos, inputDataPresInfo)
	}

	inputData["vaa01"] = info.Vaa01   // 就诊凭证编号
	inputData["Fasong"] = info.Fasong // 就诊凭证编号
	inputData["vaa07"] = info.Vaa07   // 就诊凭证编号
	inputData["bck01c"] = info.Bck01c // 就诊凭证编号
	inputData["bce02a"] = "1001"      // 就诊凭证编号

	inputData["diag"] = diags         // 就诊凭证编号
	inputData["presInfo"] = presInfos // 就诊凭证编号

	var inputLog string
	bytesData, err := json.Marshal(inputData)
	inputLog = string(bytesData)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	var url string
	gdyb_url := "http://218.104.146.179:90911/esb/listener/saveOrdInfoIp"
	url = gdyb_url

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("POST", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("code", "Xmrjyy")

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	return str, inputLog

}

func UpDatePrescriptionNumberForCoordinate(user_org_id int64, ids []int64, number string) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("user_org_id = ? AND status = 1 AND id in (?)", user_org_id, ids).Updates(map[string]interface{}{"batch_number": number, "mtime": time.Now().Unix(), "order_status": 6}).Error
	return
}

func GetDrugInfo(bbx01 string) (string, string) {

	//input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputData["bbx01"] = bbx01 // 就诊凭证编号
	inputData["name"] = ""     // 就诊凭证编号

	var inputLog string
	bytesData, err := json.Marshal(inputData)
	inputLog = string(bytesData)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	var url string
	gdyb_url := "http://218.104.146.179:9091/esb/listener/getGrug"
	url = gdyb_url

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("GET", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("code", "Xmrjyy")

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	return str, inputLog

}

func GetGoodInfo(bbx01 string) (string, string) {

	//input := make(map[string]interface{})
	inputData := make(map[string]interface{})
	inputData["bbx01"] = bbx01 // 就诊凭证编号
	inputData["name"] = ""     // 就诊凭证编号

	var inputLog string
	bytesData, err := json.Marshal(inputData)
	inputLog = string(bytesData)
	fmt.Println(string(bytesData))
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	reader := bytes.NewReader(bytesData)
	var url string
	gdyb_url := "http://218.104.146.179:9091/esb/listener/getMaterial"
	url = gdyb_url

	//url := "http://igb.hsa.gdgov.cn/ebus/gdyb_inf/poc/hsa/hgs/1101"
	request, err := http.NewRequest("GET", url, reader)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}

	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	request.Header.Set("code", "Xmrjyy")

	client := http.Client{}
	resp, err := client.Do(request)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err.Error())
		return err.Error(), ""
	}
	fmt.Println(string(respBytes))
	str := string(respBytes)
	return str, inputLog

}

func FindPatientPrescriptionInfoTwo(org_id int64, patient_id int64, record_date int64, p_type int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND p_type = ? ", org_id, record_date, patient_id, p_type).First(&info).Error
	return

}

func FindLastPatientPrescriptionInfoTwoTen(org_id int64, patient_id int64, record_date int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date < ? AND patient_id = ?", org_id, record_date, patient_id).Order("record_date desc").First(&info).Error
	return
}

func GetUnSettleHisPrescriptionFive(org_id int64, patient_id int64, record_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisOrderInfo", "status = 1").Preload("Drug", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisOrderInfo", "status = 1").Preload("HisProject").Preload("GoodInfo", "status=1").Preload("XtHisProjectTeam", "status = 1")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ? AND order_status <> 3  AND order_status <> 2  ", org_id)
	}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND order_status <> 3 and order_status <> 5  AND p_type = ?", org_id, record_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func UpdataHisPateintTwoTen(his *models.VMHisPatient) {
	writeDb.Save(&his)
}

func UpDateHisPrescriptionInfoNumberTen(user_org_id int64, id int64, number string, record_time int64, his_patient_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND his_patient_id = ? AND record_date = ?", user_org_id, his_patient_id, record_time).Updates(map[string]interface{}{"batch_number": number, "prescription_status": 3, "mtime": time.Now().Unix()}).Error

	return
}

func UpdataOrderStatusThreeTen(number string, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 5, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 5, "mtime": time.Now().Unix()}).Error
	return
}

func GetExecutionFrequencyByName(name string, org_id int64) (ef models.ExecutionFrequencyDic, err error) {
	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("(org_id = ? OR org_id = 0) AND name = ?", org_id, name).First(&ef).Error
	return
}

func GetWayInfoByName(name string, org_id int64) (ef models.HisProject, err error) {
	err = readDb.Model(&models.HisProject{}).Where("user_org_id = ? AND project_name = ? AND status= 1 AND cost_classify = 100", org_id, name).First(&ef).Error
	return
}
