package repository

import (
	"gin-vue-admin/common"
	"gin-vue-admin/models"
	"gin-vue-admin/utils"
)

func GetClientPayMealListRepository(chainIDStr, hospitalIDStr string) (interface{}, error) {

	db, err := common.NewAccountConn()
	if err != nil {
		return nil, err
	}

	chainID, err := utils.GetChainIDByStr(db, chainIDStr)
	if err != nil {
		return nil, err
	}
	hospitalID, err := utils.GetHospitalIDByStr(db, hospitalIDStr)
	if err != nil {
		return nil, err
	}

	var isOpen int
	err = db.QueryRow(`select count(id) from b_doctor_hospital
	where delflag = 0 and chain_id = ? and hospital_id = ?`, chainID, hospitalID).Scan(&isOpen)
	if err != nil {
		return nil, err
	}

	sqlStr := `select id, ifnull(convert(money / 1000, decimal(11,2)), 0),
year, month, day, meal_type, description,ifnull(convert(discount / 1000, decimal(11,3)),0) as discount
from con_meal_b_doctor
where delflag = 0`

	if isOpen != 0 {
		sqlStr += " and meal_type = 0 "
	}

	rows, err := db.Query(sqlStr)
	if err != nil {
		return nil, err
	}

	response := make([]models.PayMealList, 0)

	for rows.Next() {
		var temp models.PayMealList
		err = rows.Scan(&temp.ID, &temp.Money, &temp.Year, &temp.Month, &temp.Day, &temp.MealType, &temp.Description, &temp.Discount)
		if err != nil {
			return nil, err
		}
		response = append(response, temp)
	}

	return response, nil
}
