<template>
    <div>
        <button type="button" class="btn btn-primary" @click="add_company">
            新增企業
        </button>

        <br /><br />

        <div class="row">
            <div v-for="company in companies" :key="company.guid" class="col-xl-3 col-md-6 mb-4">
                <div :class="['card', 'shadow', 'h-100', 'py-2', company.level == '8' ? 'border-left-primary' : 'border-left-warning']" @click="edit_company(company.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">{{ company.company_name }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-building fa-2x text-gray-300"></i> <!-- 改為企業圖標 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>




    <!--新增企業-彈跳視窗-->
    <div>
        <dialog ref="add_Company_view" class="dialog-box">
            <div><button class="btn btn-danger" style="float:right" @click="close_add_Company_view">關閉</button>
                <h2>新增企業</h2>

            </div>

            <!-- 表單內容 -->
            <div class="form-group">
                <label for="companyName">企業名稱：</label>
                <input id="companyName" v-model="companyName" type="text" class="form-control" placeholder="請輸入企業名稱">
            </div>


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

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

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

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



const add_Company_view = ref(null);
//新增企業
const add_company = async () => {
    companyName.value = "";
    companyPhone.value = "";
    companyaccount.value = "";
    companypassword.value = "";
    add_Company_view.value?.showModal();
}
//關閉 <新增企業-彈跳視窗>
const close_add_Company_view = () => {
    add_Company_view.value?.close();
}


// 上傳企業基本資料
const companyName = ref("");
const companyPhone = ref("");
const companyaccount = ref("");
const companypassword = ref("");
const submitCompany = async () => {

    try {
        const companyData = {
            lastname: companyName.value,
            username: companyaccount.value,
            password: companypassword.value
        };
        console.log(companyData)

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

}



//獲取資料
const get_data = async () => {
    const All_Companies = await get_All_Companies();//獲取公司資訊
    set_All_Companies_data(All_Companies);
}



// 📌 獲取公司資訊
const get_All_Companies = async () => {
    if (!process.client) return; // 確保只在 client-side 執行

    //const token = localStorage.getItem("token_TCM");
    try {
        const response = await $fetch(`${$api_host}/api/Company_detail_table/get_all_campany`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                Authorization: authToken.value,
            },
        });

        console.log("✅ 獲取成功", response);
        return response
    } catch (error) {
        console.error("🔴 獲取公司資料失敗", error);
    }
};


// 設定資料
const companies = ref([]);
const set_All_Companies_data = (data) => {
    console.log(data)
    companies.value = data; // 更新公司列表
}



//編輯資料
const edit_company = async (guid) => {
    console.log(guid)
    router.push("/Lamiter_pages/Company-" + 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>