<template>
    <div>
        <h2>企業名稱 : {{ company_name }}</h2>
        <!-- 操作按鈕 -->
        <div style="height:30px;float:right ">
            <button class="btn btn-outline-warning" @click="edit_show">編輯資料</button>
        </div>
        <div class="d-flex align-items-center">
            <label for="enableSelect" >     是否啟用 </label>
            <select class="form-control" id="enableSelect" @change="enable_change" v-model="companyenable"
                style="width: 80px ;">
                <option value="Y">Y</option>
                <option value="N">N</option>
            </select>
        </div>
    </div>



    <!--編輯企業-彈跳視窗---->
    <div>
        <dialog ref="edit_Company_view" class="dialog-box">
            <div><button class="btn btn-danger" style="float:right" @click="close_edit_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="請輸入企業名稱"
                    readonly>
            </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="companyaccount">帳號：</label>
                <input id="companyaccount" v-model="companyaccount" type="text" class="form-control" readonly>
            </div>

            <!--<div class="form-group">
                <label for="enableSelect">是否啟用</label>
                <select class="form-control" id="enableSelect" @change="enable_change" v-model="companyenable"
                    style="width: 100%">
                    <option value="Y">Y</option>
                    <option value="N">N</option>
                </select>
            </div>-->
            <!-- 操作按鈕 -->
            <div class="button-group">
                <button class="btn btn-success" @click="submit_edit_Company">確認</button>
            </div>

        </dialog>
    </div>

    <!--確認是否啟用-->
    <div>
        <dialog ref="check_enable_view" class="dialog-box" style="width: 20%;" >
            <label>{{ companyenable === 'Y' ? '確認啟用?' : '確認關閉?' }}</label>
            <!-- 操作按鈕 -->
            <div class="button-group">
                <button class="btn btn-danger" @click = "enable_view_close">返回</button>
                <button class="btn btn-success" @click="submit_edit_enable">確認</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(); // 匯入
// 🔐 定義全域 token
const authToken = ref("");


//編輯企業彈窗
const edit_Company_view = ref(null);
const edit_show = async () => {
    await get_data();
    edit_Company_view.value?.showModal();
}

//關閉 <新增企業-彈跳視窗>
const close_edit_Company_view = () => {
    edit_Company_view.value?.close();
}

//關閉確認啟用視窗
const enable_view_close = async() =>{
    check_enable_view.value?.close();
}

//獲取資料
const get_data = async () => {
    const Company_data = await get_company_data()
    set_Company(Company_data);
};


// 獲取公司資料
const get_company_data = async () => {
    const route = useRoute(); // 取得當前路由資訊
    const company_guid = route.params.guid; // 提取路由中的 guid 參數

    // 確保 company_guid 存在
    if (!company_guid) {
        console.error("沒有找到公司 GUID！");
        return;
    }

    try {
        const response = await $fetch(`${$api_host}/api/Company_detail_table/get_campany-${company_guid}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
                Authorization: authToken.value, // 假設 authToken 已經在其他地方定義
            },
        });
        return response
    } catch (error) {
        console.error("獲取公司資料失敗:", error);
    }

}

//設置資料
//設置公司資料
const company_name = ref("");
const companyName = ref("");
const companyPhone = ref("");
const companyaccount = ref("");
const companyenable = ref("");
let level  =ref()
const set_Company = (data) => {
    company_name.value = data.company_name
    companyName.value = data.company_name
    companyaccount.value = data.user_name
    level = parseInt(data.level, 10);
    if (level % 2 == 0) {
        companyenable.value = 'Y'
    }
    else {
        companyenable.value = 'N'
    }
}



//編輯資料
//編輯是否啟動
const check_enable_view = ref(null);
const enable_change = async () => {
    if (companyenable.value == 'Y'){
        if (level % 2 != 0){
            level = level + 1;
            check_enable_view.value?.showModal();
        }
    }
    if (companyenable.value == 'N'){
        if (level % 2 == 0){
            level = level - 1;
            check_enable_view.value?.showModal();
        }
    }
    //console.log(level)
}

//上傳編輯啟用訊息
const submit_edit_enable = async () => {
    console.log(level)
    const route = useRoute(); // 取得當前路由資訊
    const company_guid = route.params.guid; // 提取路由中的 guid 參數
    try {
        const enable_data = {
            guid: company_guid,
            level:level.toString() 
        }; 
        const response = await fetch(`${$api_host}/api/Company_detail_table/company_enable`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: authToken.value,
            },
            body: JSON.stringify(enable_data)
        });
        check_enable_view.value?.close();
        alert('編輯成功！');
        get_data();
        
    } catch (error) {
        console.error( error);
    }
}


// 上傳編輯視窗內容
const submit_edit_Company = async () =>{
    try {
        const companyData = {
            company_name: companyName.value,
            username: companyaccount.value,
            password: companypassword.value
        };
        console.log(companyData)

       
    } catch (error) {
        alert('上傳失敗，請檢查後端！');
    }
}



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

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