<template>
    <div>
        <button type="button" class="btn btn-primary" @click="add_health_manager">
            新增健管師
        </button>
        <br /><br />
        <div>
            <p>啟用數量: {{ healther_count.enabled }} 未啟用數量: {{ healther_count.disabled }} 總數: {{ healther_count.total }}
            </p>
        </div>
        <br /><br />

        <div class="row">
            <div v-for="healther in healthers" :key="healther.guid" class="col-xl-3 col-md-6 mb-4">
                <div :class="['card', 'shadow', 'h-100', 'py-2', healther.level == '6' ? 'border-left-primary' : 'border-left-warning']" @click="go_healther_page(healther.guid)">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                    健管師名稱：
                                </div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ healther.health_name }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-user-tie fa-2x text-gray-300"></i> <!-- 改為人圖標 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!--新增管理師-彈跳視窗-->
    <div>
        <dialog ref="add_Health_view" class="dialog-box">
            <div><button class="btn btn-danger" style="float:right" @click="close_add_Health_view">關閉</button>
                <h2>新增管理師</h2>

            </div>

            <!-- 表單內容 -->
            <div class="form-group">
                <label for="healthName">健康管理師名稱：</label>
                <input v-model="healthName" type="text" class="form-control" placeholder="請輸入健管師名稱">
            </div>


            <div class="form-group">
                <label for="companyPhone">聯絡電話：</label>
                <input v-model="healthPhone" type="tel" class="form-control" placeholder="請輸入聯絡電話">
            </div>
            <div class="form-group">
                <label for="healthPhone">預設帳號：</label>
                <input v-model="healthaccount" type="text" class="form-control" placeholder="請輸入預設帳號">
            </div>
            <div class="form-group">
                <label for="healthPhone">預設密碼：</label>
                <input v-model="healthpassword" type="text" class="form-control" placeholder="請輸入預設密碼">
            </div>

            <!-- 操作按鈕 -->
            <div class="button-group">
                <button class="btn btn-success" @click="submitHealth">確認</button>
            </div>

        </dialog>
    </div>
</template>


<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from "vue-router"; //匯入路徑
const config = useRuntimeConfig();//匯入 API
const $api_host = config.public.apiHost;
const router = useRouter(); // 匯入
const authToken = ref("");// 🔐 定義全域 token

const add_Health_view = ref(null);

definePageMeta({
    layout: 'defaultmanager' // 指定自定義的佈局名稱
})

//新增健管師
const add_health_manager = async () => {
    healthName.value = "";
    healthPhone.value = "";
    healthaccount.value = "";
    healthpassword.value = "";
    add_Health_view.value?.showModal();
}

//關閉 <新增健管師-彈跳視窗>
const close_add_Health_view = () => {
    add_Health_view.value?.close();
}

// 上傳企業基本資料
const healthName = ref("");
const healthPhone = ref("");
const healthaccount = ref("");
const healthpassword = ref("");
const submitHealth = async () => {

    try {
        const healthData = {
            lastname: healthName.value,
            username: healthaccount.value,
            password: healthpassword.value,
            company_guid: company_guid.value
        };
        console.log(healthData)

        const response = await $fetch(`${$api_host}/api/Health_detail_table/Add_health`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: authToken.value,
            },
            body: JSON.stringify(healthData)
        });
        add_Health_view.value?.close();
        alert('上傳成功！');
        get_data();
    } catch (error) {
        console.error(error);
        alert('上傳失敗，請檢查後端！');
    }

}



const company_guid = ref("") //企業GUID
//獲取資料
const get_data = async () => {
    await get_company_basic_data();
    const All_Health_data = await get_all_health_data();
    set_All_Health_data(All_Health_data);
    const All_Count = await get_all_count();
    set_All_Health_Count(All_Count);
}

// 獲取企業基礎資料
const get_company_basic_data = async () => {
    try {

        const response = await $fetch(`${$api_host}/Users/token_check_user`, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                Authorization: authToken.value,
            },
        });
        company_guid.value = response.guid
    } catch (error) {
        console.error('企業基礎資料失敗:', error);
    }
}

// 獲取所有健康管理師資料
const get_all_health_data = async () => {

    try {
        const response = await $fetch(`${$api_host}/api/Health_detail_table/get_company_all_health-${company_guid.value}`, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                Authorization: authToken.value,
            },
        });
        return response;
    } catch (error) {
        console.error(error);
    }
}

//獲取建管師數量
const get_all_count = async () => {
    try {
        const response = await $fetch(`${$api_host}/api/Health_detail_table/get_company_all_health_count-${company_guid.value}`, {
            method: 'GET',
            headers: {
                "Content-Type": "application/json",
                Authorization: authToken.value,
            },
        });
        return response;
    } catch (error) {
        console.error(error);
    }
}

//設置資料
//設置健管師資料
const healthers = ref([]);
const set_All_Health_data = (data) => {
    console.log(data)
    healthers.value = data
}

//設置健管師數量
const healther_count = ref({ enabled: 0, disabled: 0, total: 0, });
const set_All_Health_Count = (data) => {
    let all_count = 0;
    for (let i = 0; i < data.length; i++) {
        let d = data[i];
        if (d.level == '5') {
            healther_count.value.disabled = d.level_count; // 设定未启用数量
        }
        if (d.level == '6') {
            healther_count.value.enabled = d.level_count; // 设定启用数量
        }
        all_count += d.level_count; // 累加总数
    }
    healther_count.value.total = all_count
    console.log(healther_count)
}



//前往詳細頁面
const go_healther_page =(guid) =>{
    router.push("/Manage_pages/health_person-" + guid);
}


// 自啟
// 🚀 在 mounted 時獲取 token
onMounted(() => {
    if (process.client) {
        // 讀取 localStorage 並將 token 設置到 reactive 變數中
        authToken.value = localStorage.getItem("token_TCM") || "";
    }

    get_data(); // 確保 token 讀取後再調用 API
});
</script>




<style>
/* 簡單美化對話框 */
.dialog-box {
    width: 50%;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.form-group {
    margin-bottom: 10px;
}

.form-control {
    width: 100%;
    padding: 8px;
    margin-top: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

.button-group {
    display: flex;
    justify-content: center;
    /* 讓按鈕水平置中 */
    margin-top: 15px;
}
</style>