<script setup>
import { onMounted, ref } from 'vue'

import { showToast,showSuccessToast } from 'vant';

import { setAuthUser , delAuthUser , getAuthUsers } from '@/api'

const form = ref({
  user_id: '',
  a_hour: 1
})

const onSubmit = async () =>{
  let res = await setAuthUser(form.value);
  
  if(res.code!==200){
    return showToast.fail('授權失敗,'+res.data);
  }

  genAuthList();

  return showSuccessToast('授權成功');
}

//授權清單
const authList = ref([]);


const genAuthList = async()=>{
  let res = await getAuthUsers();

  if(res.code===200){
    authList.value = res.data;
  }
}

const handleDelete = async (id)=>{
  
  let res = await delAuthUser(id);

  console.log(res)

  if(res.code!==200){
    return showToast.fail('刪除失敗');
  }

  genAuthList();

  return showSuccessToast('刪除成功');

}

onMounted(()=>{
  genAuthList();
})

</script>

<template>
  <div class="auth page">
    <van-nav-bar class="bg-skyBlue py-1" left-arrow @click-left="$router.push('/')">
      <template #title>
        <h5 class="text-white mb-1"><strong>授權商務卡片編輯</strong></h5>
      </template>
      <template #left>
        <h4><i class="fa-solid fa-angle-left text-white" :style="{ opacity: 0.5 }"></i></h4>
      </template>
    </van-nav-bar>

    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <van-field
            v-model="form.user_id"
            label="會員編號"
            name="pattern"
            placeholder="請輸入想授權的會員編號"
            label-width="100"
            :rules="[{ required: true, message: '會員編號為必填' }]"
          />
          <van-field
            v-model="form.a_hour"
            label="授權時間(小時)"
            name="pattern"
            placeholder="請輸入想授權的時間"
            label-width="100"
            :rules="[{ required: true, message: '授權時間為必填' }]"
          />
          <div class="p-3">
            <van-button block class="btn-darkBlue" native-type="submit"><i class="fa-solid fa-hand"></i> 確認送出授權</van-button>
          </div>
        </van-cell-group>      

        <van-cell-group inset>
          <table id="auth-list">
            <thead>
              <tr>
                <th>授權會員</th>
                <th>授權時間</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="v of authList" :key="v.id">
                <td>{{v.user_id}}</td>
                <td>{{v.auth_time}}</td>
                <td @click="handleDelete(v.id)">刪除</td>
              </tr>
            </tbody>
          </table>
        </van-cell-group>
      </van-form>
    </div>
    
  </div>
</template>

<style src="@/assets/css/main.css"></style>

<style lang="less" scoped>
  table#auth-list{
    width: 100%;
    thead th{
      color: #fff;
      background-color: #4a677d;
    }
    tr:nth-child(even){
      background-color: #f2f2f2;
    }
    th,td{
      padding: 5px 10px;
    }
  }
</style>