package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/shopspring/decimal"
	"strconv"
	"strings"
	"time"
)

type HisDepositApiController struct {
	BaseAuthAPIController
}

func HisDepositApiRegistRouters() {
	//beego.Router("/api/his/ttt", &HisDepositApiController{}, "get:TTT")                         //测试接口
	beego.Router("/api/his/gethisusertoalive", &HisDepositApiController{}, "get:GetHisUserToAlive")  //获取病例中心,有效患者名称(去除了转出和死亡的)
	beego.Router("/api/his/gethisuser", &HisDepositApiController{}, "get:GetHisUser")                //获取病例中心,有效患者名称
	beego.Router("/api/his/adddeposit", &HisDepositApiController{}, "post:AddDeposit")               //新增押金
	beego.Router("/api/his/getdepositcode", &HisDepositApiController{}, "get:GetDepositCode")        //获取新增押金编号
	beego.Router("/api/his/getdeletecode", &HisDepositApiController{}, "get:GetDeleteCode")          //获取退款编号
	beego.Router("/api/his/rechargedetails", &HisDepositApiController{}, "get:RechargeDetails")      //充值明细列表
	beego.Router("/api/his/updeposit", &HisDepositApiController{}, "get:UpDeposit")                  //押金审核
	beego.Router("/api/his/deletehistory", &HisDepositApiController{}, "get:DeleteHistory")          //押金删除
	beego.Router("/api/his/rechargesummary", &HisDepositApiController{}, "get:RechargeSummary")      //充值汇总列表
	beego.Router("/api/his/getuserlist", &HisDepositApiController{}, "get:GetUserList")              //获取患者押金列表
	beego.Router("/api/his/depositflow", &HisDepositApiController{}, "get:DepositFlow")              //根据患者id获取押金流水
	beego.Router("/api/his/deductiondetails", &HisDepositApiController{}, "get:DeductionDetails")    //扣费明细查询
	beego.Router("/api/his/desummary", &HisDepositApiController{}, "get:DeSummary")                  //扣费汇总
	beego.Router("/api/his/idtobalance", &HisDepositApiController{}, "get:IdToBalance")              //根据患者id查询患者的余额
	beego.Router("/api/his/refundapplication", &HisDepositApiController{}, "post:RefundApplication") //新增一条退款申请
	beego.Router("/api/his/refundreview", &HisDepositApiController{}, "get:RefundReview")            //退款审核通过/拒绝
	beego.Router("/api/his/deleterefund", &HisDepositApiController{}, "get:DeleteRefund")            //退款删除
	beego.Router("/api/his/changerefund", &HisDepositApiController{}, "post:ChangeRefund")           //更改退款申请
	beego.Router("/api/his/refundlist", &HisDepositApiController{}, "get:RefundList")                //退款分页
	beego.Router("/api/his/getorgname", &HisDepositApiController{}, "get:GetorgName")                //获取供应商名字
	beego.Router("/api/his/getweektime", &HisDepositApiController{}, "get:GetWeekTime")              //获取本周时间
	beego.Router("/api/his/getmonthtime", &HisDepositApiController{}, "get:GetMonthTime")            //获取本月时间
}

//func (this *HisDepositApiController) TTT() {
//	orgid := this.GetAdminUserInfo().CurrentOrgId
//	id, _ := this.GetInt64("id")
//	code := this.GetString("code")
//	deposit,_ := this.GetInt64("depostit")
//	err := service.MoneyIncrease(orgid,id,code,deposit)
//	if err != nil {
//
//	}
//	this.ServeSuccessJSON(map[string]interface{}{
//		"list": "成功",
//	})
//	return
//}

//获取病例中心,有效患者名称(去除了转出和死亡的)
func (this *HisDepositApiController) GetHisUserToAlive() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	list, err := service.GetHisUserToAlive(orgid)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
	return
}

//获取病例中心,有效患者名称
func (this *HisDepositApiController) GetHisUser() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	token := this.Ctx.Request.Header.Get("Cookie")
	fmt.Println(token)
	list, err := service.GetHisUser(orgid)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
	})
	return
}

//新增押金
func (this *HisDepositApiController) AddDeposit() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	switch {
	case dataBody["code"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金编号不能为空")
		return
	case dataBody["his_patient_id"] == nil || dataBody["his_patient_id"] == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患者名称不能为空")
		return
	case dataBody["deposit"] == nil || dataBody["deposit"] == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额不能为空")
		return
	case dataBody["trial_status"] == nil || dataBody["trial_status"] == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "审核状态不能为空")
		return
	}
	code := dataBody["code"].(string)                             //押金编号
	his_patient_id := int64(dataBody["his_patient_id"].(float64)) //患者编号
	var tmps float64
	switch dataBody["deposit"].(type) {
	case string:
		t_deposit := dataBody["deposit"].(string)
		if len(t_deposit) > 0 {
			if t_deposit[0] == 45 {
				this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额错误")
				return
			}
		}
		tt, errs := strconv.ParseFloat(t_deposit, 64)
		if errs != nil {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额错误")
			return
		} else {
			tmps = tt
		}
	default:
		tmps = dataBody["deposit"].(float64)
	}
	if tmps == 0 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金金额不能为0")
		return
	}
	deposit := decimal.NewFromFloat(tmps) //押金金额
	var remarks string
	if dataBody["remarks"] == nil {
		remarks = ""
	} else {
		remarks = dataBody["remarks"].(string) //备注
	}
	trial_status := int64(dataBody["trial_status"].(float64)) //审核状态
	createid := this.GetAdminUserInfo().AdminUser.Id
	pp := this.GetAdminUserInfo()
	fmt.Println(pp)
	err = service.UpDeposit(code, remarks, his_patient_id, orgid, trial_status, createid, deposit)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "添加成功",
	})
	return
}

//获取新增押金编号
func (this *HisDepositApiController) GetDepositCode() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	var code string
	for a := true; a == true; {
		code = service.CreateCPCode("CP")
		tmp := service.FindDecimalCode(orgid, code)
		if tmp == false {
			a = false
		}
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": code,
	})
	return
}

//获取退款编号
func (this *HisDepositApiController) GetDeleteCode() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	var code string
	for a := true; a == true; {
		code = service.CreateCPCode("AF")
		tmp := service.FindDecimalCode(orgid, code)
		if tmp == false {
			a = false
		}
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": code,
	})
	return
}

//充值明细列表
func (this *HisDepositApiController) RechargeDetails() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	var stime int64 //开始时间
	var etime int64 //结束时间

	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	if start_time == "" && end_time == "" {
		//如果为空查询全部的
		_, etime = service.GetMondayOfWeek()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	list, err := service.DetailsList(orgid, stime, etime, keyword, slicekey)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	var sum decimal.Decimal
	for i := 0; i < len(list); i++ {
		if list[i].TrialStatus == 1 {
			sum = sum.Add(list[i].Deposit)
		}
		list[i].Name = service.GetCreateidName(list[i].CreateId, orgid)
		list[i].HisName = namemap[list[i].HisPatientId]
		list[i].Starttime = fmt.Sprintf(time.Unix(list[i].Ctime, 0).Format("2006-01-02"))
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": list,
		"sum":  sum,
	})
	return
}

//充值汇总列表
func (this *HisDepositApiController) RechargeSummary() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	var stime int64 //开始时间
	var etime int64 //结束时间
	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	if start_time == "" && end_time == "" {
		_, etime = service.GetMondayOfWeek()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	list, err := service.SummaryList(orgid, stime, etime, keyword, slicekey)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	//list为详细数据,把list整理合并为maplist输出
	maplist := make(map[int64]models.Summary)
	Finlist := []models.Summary{}
	tmpslice := make([]int64, 0)
	var sum decimal.Decimal
	for i := 0; i < len(list); i++ {
		if list[i].TrialStatus == 1 {
			if k, ok := maplist[list[i].HisPatientId]; ok {
				k.SumDecimal = k.SumDecimal.Add(list[i].Deposit)
				maplist[list[i].HisPatientId] = models.Summary{
					namemap[list[i].HisPatientId],
					k.SumDecimal,
					service.GetUserMoney(list[i].HisPatientId, orgid),
				}
			} else {
				maplist[list[i].HisPatientId] = models.Summary{
					namemap[list[i].HisPatientId],
					list[i].Deposit,
					service.GetUserMoney(list[i].HisPatientId, orgid),
				}
				tmpslice = append(tmpslice, list[i].HisPatientId)
			}
			sum = sum.Add(list[i].Deposit)
		}
	}
	//maplist虽然满足接口要求,但格式不行,整理为Finlist输出
	for i := 0; i < len(tmpslice); i++ {
		Finlist = append(Finlist, maplist[tmpslice[i]])
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": Finlist,
		"sum":  sum,
	})
	return
}

//审核
func (this *HisDepositApiController) UpDeposit() {
	id, _ := this.GetInt64("id", 0)
	if id == 0 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "id不能为空")
		return
	}
	tmp, err := service.GetDecimalHistoryOne(id)
	if err != nil {
		utils.ErrorLog("无法查询该记录信息", err.Error())
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "无法查询该记录信息")
		return
	}
	if tmp.TrialStatus == 0 {
		err = service.UpDecimalHistory(id)
		if err != nil {
			utils.ErrorLog("更新押金历史表出错,原因为:", err.Error())
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "系统错误")
			return
		}
	} else {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "当前状态不可审核")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "审核通过",
	})
	return
}
func (this *HisDepositApiController) DeleteHistory() {
	id, _ := this.GetInt64("id", 0)
	if id == 0 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "id不能为空")
		return
	}
	tmp, err := service.GetDecimalHistoryOne(id)
	if err != nil {
		utils.ErrorLog("无法查询该记录信息", err.Error())
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "无法查询该记录信息")
		return
	}
	if tmp.TrialStatus == 0 {
		err = service.DelDecimalHistory(id)
		if err != nil {
			utils.ErrorLog("删除历史记录出错,原因为:", err.Error())
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "系统错误")
			return
		}
	} else {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "已审核的单据不能进行删除操作")
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "删除成功",
	})
	return
}

//根据id获取押金流水
func (this *HisDepositApiController) DepositFlow() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	check := map[string][]string{
		"id":             {"must", "int", "id"},
		"deposit_status": {"must", "int", "deposit_status"},
		"page":           {"must", "string", "page"},
		"limit":          {"must", "string", "limit"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	id, _ := this.GetInt64("id") //患者id
	//获取当前患者的姓名
	tmp, _ := service.GetHisUserName(orgid, id)
	name := tmp.Name
	deposit_status, _ := this.GetInt64("deposit_status", 0) //押金类型
	if deposit_status > 4 {
		utils.ErrorLog("押金类型错误,deposit_status:", deposit_status)
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "押金类型错误")
		return
	}
	start_time := this.GetString("start_time", "") //开始时间
	end_time := this.GetString("end_time", "")     //结束时间
	page, _ := this.GetInt64("page")               //页码
	limit, _ := this.GetInt64("limit")             //每一页查出来的条数
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var stime int64 //开始时间
	var etime int64 //结束时间
	if start_time == "" && end_time == "" {
		//如果为空则查全部的
		_, etime = service.GetMonth()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	//获取该角色当前时间段的余额
	decimal := service.GetMoneyforTime(id, orgid, etime)
	//获取列表
	deposirhistory, total, errs := service.GetFlowList(page, limit, id, orgid, stime, etime, deposit_status)
	if errs != nil {
		utils.ErrorLog("获取列表失败,原因为:", errs.Error())
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, errs.Error())
		return
	}
	for i := 0; i < len(deposirhistory); i++ {
		//如果为扣费,或退费 则把订单id变为就诊号
		if deposirhistory[i].DepositStatus == 2 || deposirhistory[i].DepositStatus == 4 {
			tmpcode, _ := strconv.ParseInt(deposirhistory[i].DepositCode, 10, 64)
			deposirhistory[i].DepositCode = service.FindcodeToid(tmpcode)
		}
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"list":    deposirhistory,
		"name":    name,
		"decimal": decimal,
		"total":   total,
	})
	return
}

//获取患者押金列表
func (this *HisDepositApiController) GetUserList() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	keyword := this.GetString("keyword")
	page, _ := this.GetInt64("page")   //页码
	limit, _ := this.GetInt64("limit") //每一页查出来的条数
	check := map[string][]string{
		"page":  {"must", "string", "page"},
		"limit": {"must", "string", "limit"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	list, total, errs := service.GetUserList(page, limit, orgid, keyword, slicekey)
	if errs != nil {
		utils.ErrorLog(errs.Error())
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	for i := 0; i < len(list); i++ {
		list[i].HisPatientName = namemap[list[i].HisPatientId]
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":  list,
		"total": total,
	})
	return
}

//扣费明细查询
func (this *HisDepositApiController) DeductionDetails() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	var stime int64 //开始时间
	var etime int64 //结束时间

	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	if start_time == "" && end_time == "" {
		_, etime = service.GetMondayOfWeek()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	list, err := service.DeductionList(orgid, stime, etime, keyword, slicekey)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}

	var sum decimal.Decimal
	var detailslist []models.Details
	var details models.Details
	for i := 0; i < len(list); i++ {
		sum = sum.Add(list[i].Deposit)
		tmp_id, _ := strconv.ParseInt(list[i].DepositCode, 10, 64)
		details.ID = tmp_id
		details.Code = service.FindcodeToid(tmp_id)
		details.NameId = list[i].HisPatientId
		details.Name = namemap[list[i].HisPatientId]
		details.Number = service.FindnumberToid(tmp_id)
		details.Decimal = list[i].Deposit
		details.ChargeDate = fmt.Sprintf(time.Unix(list[i].Ctime, 0).Format("2006-01-02 15:04:05"))
		details.Chargetype = service.CodeToChargetype(orgid, details.Code)
		details.Total = service.MedicalTotal(orgid, tmp_id)
		details.ButtonShow = service.IsButtonShow(list[i].DepositCode, orgid, list[i].HisPatientId)
		detailslist = append(detailslist, details)
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"list": detailslist,
		"sum":  sum,
	})
	return
}

//扣费汇总
func (this *HisDepositApiController) DeSummary() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	var stime int64 //开始时间
	var etime int64 //结束时间

	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	if start_time == "" && end_time == "" {
		_, etime = service.GetMondayOfWeek()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	list, err := service.DeductionList(orgid, stime, etime, keyword, slicekey)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	var sum decimal.Decimal
	var detailslist []models.DeductionSummary
	var details models.DeductionSummary
	for i := 0; i < len(list); i++ {
		sum = sum.Add(list[i].Deposit)
		details.Name = namemap[list[i].HisPatientId]
		details.Decimal = list[i].Deposit
		tmp_id, _ := strconv.ParseInt(list[i].DepositCode, 10, 64)
		details.Total = service.MedicalTotal(orgid, tmp_id)
		detailslist = append(detailslist, details)
	}
	maplist := make(map[string]models.DeductionSummary)
	Finlist := []models.DeductionSummary{}
	tmpslice := make([]string, 0)
	for i := 0; i < len(detailslist); i++ {
		if k, ok := maplist[detailslist[i].Name]; ok {
			k.Total = k.Total.Add(detailslist[i].Total)
			k.Decimal = k.Decimal.Add(detailslist[i].Decimal)
			maplist[detailslist[i].Name] = models.DeductionSummary{
				detailslist[i].Name,
				k.Total,
				k.Decimal,
			}
		} else {
			maplist[detailslist[i].Name] = models.DeductionSummary{
				detailslist[i].Name,
				detailslist[i].Total,
				detailslist[i].Decimal,
			}
			tmpslice = append(tmpslice, detailslist[i].Name)
		}
	}
	for i := 0; i < len(tmpslice); i++ {
		Finlist = append(Finlist, maplist[tmpslice[i]])
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": Finlist,
		"sum":  sum,
	})
	return
}

//根据患者id查询患者的余额
func (this *HisDepositApiController) IdToBalance() {
	check := map[string][]string{
		"his_patient_id": {"must", "int", "his_patient_id"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	orgid := this.GetAdminUserInfo().CurrentOrgId
	his_patient_id, _ := this.GetInt64("his_patient_id")
	tmp := service.GetUserMoney(his_patient_id, orgid)
	this.ServeSuccessJSON(map[string]interface{}{
		"list": tmp,
	})
	return
}

//新增一条退款申请
func (this *HisDepositApiController) RefundApplication() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	createid := this.GetAdminUserInfo().AdminUser.Id
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	switch {
	case dataBody["code"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "申请编号不能为空")
		return
	case dataBody["his_patient_id"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患者名称不能为空")
		return
	case dataBody["deposit"] == nil || dataBody["deposit"] == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额不能为空")
		return
	case dataBody["trial_status"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "审核状态不能为空")
		return
	}
	code := dataBody["code"].(string)                             //申请编号
	his_patient_id := int64(dataBody["his_patient_id"].(float64)) //患者编号
	//deposit := decimal.NewFromFloat(dataBody["deposit"].(float64)) //退款金额
	var tmps float64
	switch dataBody["deposit"].(type) {
	case string:
		t_deposit := dataBody["deposit"].(string)
		if len(t_deposit) > 0 {
			if t_deposit[0] == 45 {
				this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额错误")
				return
			}
		}
		tt, errs := strconv.ParseFloat(t_deposit, 64)
		if errs != nil {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额错误")
			return
		} else {
			tmps = tt
		}
	default:
		tmps = dataBody["deposit"].(float64)
	}
	if tmps == 0 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额不能为0")
		return
	}
	deposit := decimal.NewFromFloat(tmps)                     //押金金额
	trial_status := int64(dataBody["trial_status"].(float64)) //审核状态

	err = service.RefundApplication(orgid, his_patient_id, trial_status, createid, code, deposit)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "新增成功",
	})
	return

}

//退款审核通过/拒绝
func (this *HisDepositApiController) RefundReview() {
	check := map[string][]string{
		"ids":          {"must", "string", "ids"},
		"trial_status": {"must", "int", "trial_status"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	orgid := this.GetAdminUserInfo().CurrentOrgId
	ids := this.GetString("ids") //很多id

	trial_status, _ := this.GetInt64("trial_status")
	if trial_status != 1 && trial_status != 2 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "参数trial_status值错误")
		return
	}
	err = service.RefundReviewMore(orgid, trial_status, ids)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	var tmplist string
	if trial_status == 1 {
		tmplist = "审核通过"
	} else {
		tmplist = "审核拒绝"
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": tmplist,
	})
	return
}

//退款删除
func (this *HisDepositApiController) DeleteRefund() {
	check := map[string][]string{
		"id": {"must", "int", "id"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	orgid := this.GetAdminUserInfo().CurrentOrgId
	id, _ := this.GetInt64("id")
	err = service.DeleteRefund(orgid, id)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "删除成功",
	})
	return
}

//更改退款申请
func (this *HisDepositApiController) ChangeRefund() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	if err != nil {
		utils.ErrorLog(err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	switch {
	case dataBody["id"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "id不能为空")
		return
	case dataBody["code"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "申请编号不能为空")
		return
	case dataBody["his_patient_id"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "患者名称不能为空")
		return
	case dataBody["deposit"] == nil || dataBody["deposit"] == "":
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额不能为空")
		return
	case dataBody["trial_status"] == nil:
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "审核状态不能为空")
		return
	}
	id := int64(dataBody["id"].(float64))
	code := dataBody["code"].(string)                             //申请编号
	his_patient_id := int64(dataBody["his_patient_id"].(float64)) //患者编号
	//deposit := decimal.NewFromFloat(dataBody["deposit"].(float64)) //退款金额
	var tmps float64
	switch dataBody["deposit"].(type) {
	case string:
		t_deposit := dataBody["deposit"].(string)
		if len(t_deposit) > 0 {
			if t_deposit[0] == 45 {
				this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额错误")
				return
			}
		}
		tt, errs := strconv.ParseFloat(t_deposit, 64)
		if errs != nil {
			this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额错误")
			return
		} else {
			tmps = tt
		}
	default:
		tmps = dataBody["deposit"].(float64)
	}
	if tmps == 0 {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, "退款金额不能为0")
		return
	}
	deposit := decimal.NewFromFloat(tmps)                     //押金金额
	trial_status := int64(dataBody["trial_status"].(float64)) //审核状态
	err = service.ChangeRefund(orgid, his_patient_id, trial_status, id, code, deposit)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list": "保存成功",
	})
	return
}

//退款分页
func (this *HisDepositApiController) RefundList() {
	check := map[string][]string{
		"refundtype":  {"must", "int", "refundtype"},
		"examinetype": {"must", "int", "examinetype"},
		"page":        {"must", "string", "page"},
		"limit":       {"must", "string", "limit"},
	}
	_, err := checks(this, &check)
	if err != nil {
		this.ServeFailJsonSend(enums.ErrorCodeParamWrong, err.Error())
		return
	}
	orgid := this.GetAdminUserInfo().CurrentOrgId
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	keyword := this.GetString("keyword")           //获取搜索框
	refundtype, _ := this.GetInt64("refundtype")   //获取退款类型
	examinetype, _ := this.GetInt64("examinetype") //获取审核状态
	page, _ := this.GetInt64("page")               //页码
	limit, _ := this.GetInt64("limit")             //每一页查出来的条数
	start_time := this.GetString("start_time")
	end_time := this.GetString("end_time")
	var stime int64 //开始时间
	var etime int64 //结束时间

	namemap := make(map[int64]string)
	slicekey := make([]int64, 0)
	lists, _ := service.GetHisUser(orgid)
	for _, v := range lists {
		namemap[v.ID] = v.Name
	}
	if len(keyword) > 0 {
		for k, v := range namemap {
			res := strings.Contains(v, keyword)
			if res == true {
				slicekey = append(slicekey, k)
			}
		}
	}
	if start_time == "" && end_time == "" {
		stime, etime = service.GetMondayOfWeek()
		stime = 0
	} else {
		stmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
		etmp, _ := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
		stime = stmp.Unix()
		etime = etmp.Unix()
	}
	depo := []models.RefundList{}
	var total int64
	depo, total, err = service.RefundList(page, limit, orgid, stime, etime, refundtype, examinetype, keyword, slicekey)
	if err != nil {
		utils.ErrorLog("查询失败,原因为:", err.Error())
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	for i := 0; i < len(depo); i++ {
		depo[i].Name = service.GetCreateidName(depo[i].CreateId, orgid)
		depo[i].HisName = namemap[depo[i].HisPatientId]
		if depo[i].Mtime > depo[i].Ctime {
			depo[i].Starttime = fmt.Sprintf(time.Unix(depo[i].Mtime, 0).Format("2006-01-02 15:04:05"))
		} else {
			depo[i].Starttime = fmt.Sprintf(time.Unix(depo[i].Ctime, 0).Format("2006-01-02 15:04:05"))
		}
		if depo[i].DepositStatus == 4 {
			depo[i].Name = "-"
			tmpcode, _ := strconv.ParseInt(depo[i].DepositCode, 10, 64)
			depo[i].DepositCode = service.FindcodeToid(tmpcode)
		}

	}
	this.ServeSuccessJSON(map[string]interface{}{
		"list":  depo,
		"total": total,
	})
	return
}

func (this *HisDepositApiController) GetorgName() {
	orgid := this.GetAdminUserInfo().CurrentOrgId
	name := service.GetorgName(orgid)
	this.ServeSuccessJSON(map[string]interface{}{
		"list": name,
	})
	return
}

//获取本月时间
func (this *HisDepositApiController) GetMonthTime() {
	stime, etime := service.GetMonth()
	srart_time := fmt.Sprintf(time.Unix(stime, 0).Format("2006-01-02"))
	end_time := fmt.Sprintf(time.Unix(etime, 0).Format("2006-01-02"))

	this.ServeSuccessJSON(map[string]interface{}{
		"srart_time": srart_time,
		"end_time":   end_time,
	})
	return
}

//获取本周时间
func (this *HisDepositApiController) GetWeekTime() {
	stime, etime := service.GetMondayOfWeek()
	srart_time := fmt.Sprintf(time.Unix(stime, 0).Format("2006-01-02"))
	end_time := fmt.Sprintf(time.Unix(etime, 0).Format("2006-01-02"))

	this.ServeSuccessJSON(map[string]interface{}{
		"srart_time": srart_time,
		"end_time":   end_time,
	})
	return
}

//判断前端参数是否为空
func checks(this *HisDepositApiController, m *map[string][]string) (map[string]string, error) {
	tmp := make(map[string]string)
	for k, v := range *m {
		t := this.GetString(k)
		if v[0] == "must" && t == "" {
			return nil, fmt.Errorf(v[2] + "不能为空")
		}
		tmp[k] = t
	}
	return tmp, nil
}