package mcu_corporate_services

import (
	"cpone/db"
	"cpone/models"
	dbx "cpone/package/database"
	"fmt"
	"strconv"

	"go.uber.org/zap"
)

type TabKepersertaanServices struct {
	TabKepersertaanServiceStore db.AppStore
}

func NewTabKepersertaanService(store db.AppStore) *TabKepersertaanServices {
	return &TabKepersertaanServices{
		TabKepersertaanServiceStore: store,
	}
}

func (tkp *TabKepersertaanServices) GetPieChartConf(title string, subtext string, data []models.SeriesData) (models.Piechart, error) {

	option := models.Piechart{
		Title: struct {
			Text    string `json:"text"`
			SubText string `json:"subtext"`
			Left    string `json:"left"`
		}{
			Text:    title,
			SubText: subtext,
			Left:    "center",
		},
		Tooltip: struct {
			Trigger string `json:"trigger"`
		}{
			Trigger: "item",
		},
		Legend: struct {
			Top    string `json:"top"`
			Left   string `json:"left"`
			Orient string `json:"orient"`
			Height int    `json:"height"`
		}{
			Top:    "bottom",
			Left:   "center",
			Orient: "vertical",
			Height: 75,
		},
		Series: []models.Series{
			{
				Label: struct {
					Position  string `json:"position"`
					Formatter string `json:"formatter"`
				}{
					Position:  "inner",
					Formatter: "{d}%",
				},
				Name:   "Access From",
				Type:   "pie",
				Radius: []string{"20%", "50%"},
				ItemStyle: struct {
					BorderRadius int    `json:"borderRadius"`
					BorderColor  string `json:"borderColor"`
					BorderWidth  int    `json:"borderWidth"`
				}{
					BorderRadius: 10,
					BorderColor:  "#fff",
					BorderWidth:  2,
				},
				Data: data,
				Emphasis: struct {
					ItemStyle struct {
						ShadowBlur    int    `json:"shadowBlur"`
						ShadowOffsetX int    `json:"shadowOffsetX"`
						ShadowColor   string `json:"shadowColor"`
					} `json:"itemStyle"`
				}{
					ItemStyle: struct {
						ShadowBlur    int    `json:"shadowBlur"`
						ShadowOffsetX int    `json:"shadowOffsetX"`
						ShadowColor   string `json:"shadowColor"`
					}{
						ShadowBlur:    10,
						ShadowOffsetX: 0,
						ShadowColor:   "rgba(0, 0, 0, 0.5)",
					},
				},
			},
		},
	}

	return option, nil
}

func (tkp *TabKepersertaanServices) GetTotalKepesertaanMCU(mcuID string) (models.Piechart, error) {
	logger, _ := zap.NewProduction()
	var option models.Piechart
	var data models.TotalPesertaModel

	q := `
		SELECT 
		COUNT(distinct(T_OrderHeaderID)) as peserta,
		COUNT( distinct(Mcu_PreregisterPatientsM_PatientID)) as total
		FROM mcu_preregister_patients
		LEFT JOIN t_orderheader ON Mcu_PreregisterPatientsT_OrderHeaderID = T_OrderHeaderID AND
		T_OrderHeaderIsActive = 'Y'
		WHERE
		Mcu_PreregisterPatientsMgm_McuID = ? AND
		Mcu_PreregisterPatientsIsActive = 'Y'
	`

	if err := dbx.Handlex.Get(&data, q, mcuID); err != nil {
		return option, fmt.Errorf("error get total participant %v", err)
	}
	defer logger.Sync()
	logger.Info("resp data", zap.Any("data", data))

	title := "Peserta MCU"
	subtext := "Total Peserta " + strconv.Itoa(data.Total)
	chartData := []models.SeriesData{}

	if data.Total == 0 {
		chartData = append(chartData, models.SeriesData{Value: 0, Name: "No Data"})
	} else {
		chartData = []models.SeriesData{
			{
				Value: data.Peserta,
				Name:  "Sudah MCU: " + strconv.Itoa(data.Peserta) + " peserta",
			},
			{
				Value: data.Total - data.Peserta,
				Name:  "Belum MCU: " + strconv.Itoa(data.Total-data.Peserta) + " peserta",
			},
		}
	}

	option, err := tkp.GetPieChartConf(title, subtext, chartData)
	if err != nil {
		return option, fmt.Errorf("error get piechart total peserta: %v", err)
	}

	return option, nil
}

func (tkp *TabKepersertaanServices) GetKepesertaanByGender(mcuID string) (models.Piechart, error) {
	logger, _ := zap.NewProduction()
	var option models.Piechart
	var data []models.GenderPesertaModel

	title := "Peserta MCU"
	subtext := "Berdasarkan jenis kelamin"
	chartData := []models.SeriesData{}

	q := `
		SELECT IF(M_PatientGender = 'male','Laki-laki','Perempuan') as M_PatientGender,
		COUNT(T_OrderHeaderID) as Jumlah
		FROM t_orderheader
		LEFT JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID  AND M_PatientIsActive = 'Y'
		WHERE T_OrderHeaderMgm_McuID = ? AND T_OrderHeaderIsActive = 'Y'
		GROUP BY M_PatientGender
	`

	if err := dbx.Handlex.Select(&data, q, mcuID); err != nil {
		return option, fmt.Errorf("error get total gender %v", err)
	}
	defer logger.Sync()
	logger.Info("resp data", zap.Any("data", data))

	if data != nil {
		for _, d := range data {
			chartData = append(chartData, models.SeriesData{
				Value: d.Jumlah,
				Name:  d.M_PatientGender + ": " + strconv.Itoa(d.Jumlah) + " Peserta",
			})
		}
	} else {
		chartData = append(chartData, models.SeriesData{Value: 0, Name: "No Data"})
	}

	option, err := tkp.GetPieChartConf(title, subtext, chartData)
	if err != nil {
		return option, fmt.Errorf("error get piechart total gender: %v", err)
	}

	return option, nil
}

func (tkp *TabKepersertaanServices) GetKepesertaanByUmur(mcuID string) (models.Piechart, error) {
	logger, _ := zap.NewProduction()
	var option models.Piechart
	var data []models.UmurPesertaModel

	title := "Peserta MCU"
	subtext := "Berdasarkan umur"
	chartData := []models.SeriesData{}

	q := `
		SELECT
		CASE 
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) < '30'  THEN  "1. < 30 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) >=    '30' AND left(T_OrderHeaderM_PatientAge,2)  < '40'  THEN   "2. 30 -< 40 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) >=   '40' AND  left(T_OrderHeaderM_PatientAge,2)  < '50'  THEN   "3. 40 - < 50 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2)   >= '50' THEN   "4. > 50 tahun" ELSE  "" 
		END AS umur,
		COUNT(T_OrderHeaderID) as total
		FROM t_orderheader
		LEFT JOIN m_patient ON T_OrderHeaderM_PatientID = M_PatientID  AND M_PatientIsActive = 'Y'
		WHERE t_orderheaderMgm_McuID = ? AND T_OrderHeaderIsActive = 'Y'
		GROUP BY
		CASE 
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) < '30'  THEN  "1. < 30 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) >=    '30' AND left(T_OrderHeaderM_PatientAge,2)  < '40'  THEN   "2. 30 -< 40 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2) >=   '40' AND  left(T_OrderHeaderM_PatientAge,2)  < '50'  THEN   "3. 40 - < 50 tahun"  
			WHEN LEFT(T_OrderHeaderM_PatientAge,2)   >= '50' THEN   "4. > 50 tahun" ELSE  "" 
		END
		ORDER BY umur
	`

	if err := dbx.Handlex.Select(&data, q, mcuID); err != nil {
		return option, fmt.Errorf("error get data jumlah umur: %v", err)
	}
	defer logger.Sync()
	logger.Info("response data", zap.Any("data", data))

	if data != nil {
		for _, d := range data {
			chartData = append(chartData, models.SeriesData{
				Value: d.Total,
				Name:  d.Umur + ": " + strconv.Itoa(d.Total) + " Peserta",
			})
		}
	} else {
		chartData = append(chartData, models.SeriesData{Value: 0, Name: "No Data"})
	}

	option, err := tkp.GetPieChartConf(title, subtext, chartData)
	if err != nil {
		return option, fmt.Errorf("error get piechart jumlah umur: %v", err)
	}

	return option, nil
}

func (tkp *TabKepersertaanServices) GetChartRenderPeserta(mcuID string) ([]models.McuTabModels, error) {
	var ret []models.McuTabModels

	q := `
	SELECT
	Mcu_ImageGrafikGroupResult,
	Mcu_ImageGrafikGroupMenu,
	Mcu_ImageGrafikName,
	Mcu_ImageGrafikJsonRender
	FROM mgm_mcugrafik
	JOIN mcu_image_grafik ON Mcu_ImageGrafikID = Mgm_McuGrafikMcu_ImageGrafikID
	WHERE Mgm_McuGrafikMgm_McuID = ?
	AND Mcu_ImageGrafikGroupMenu = "PESERTA"
	AND Mgm_McuGrafikIsActive = 'Y'
	ORDER BY Mcu_ImageGrafikID
	`
	if err := dbx.Handlex.Select(&ret, q, mcuID); err != nil {
		return ret, fmt.Errorf("error get data tab peserta: %v", err)
	}

	return ret, nil
}
