<script setup>
import { ref, reactive, watch, onMounted } from "vue";
import { useMainStore } from "@/stores/store";
import { useI18n } from "vue-i18n";
import { VDataTable } from "vuetify/labs/VDataTable";
import VueDatePicker from "@vuepic/vue-datepicker";
import "@vuepic/vue-datepicker/dist/main.css";
import axios from "axios";
import moment from "moment";

const { t } = useI18n();
const store = useMainStore();

let token = store.token;
let loading = ref(false);
let title = ref(null);
let isCheck = ref(null);
let pageNum = ref(1); // 頁數(預設第一頁)
let pageAmount = ref(5); // 每頁顯示筆數
let totalPages = ref(1); // 總頁數
let courses = reactive({
  list: [],
});
let classes = reactive({
  list: [],
});

// 搜尋
let searchInput = ref("");
let searchState = ref(false);

watch(pageNum, () => {
  getClass();
});

// 取得開課紀錄
async function getClass() {
  console.log("getClass");
  loading.value = true;
  let token = store.token;
  let url = `${store.apiUrl}/api/get_class_name?access_token=${token}&page_num=${pageNum.value}&page_amount=${pageAmount.value}`;

  if (isCheck.value) {
    url += `&is_check=${isCheck.value}`;
  }

  if (searchState.value) {
    url += `&keyword=${searchInput.value}`;
  }

  try {
    let response = await axios.get(url);
    classes.list = response.data.classes;
    totalPages.value = store.getTotalPages(response.data.total_num, 5);

    setTimeout(() => {
      loading.value = false;
    }, 500);

    console.log("開課資料", classes.list);
  } catch (error) {
    console.error(error);
  }
}

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

// 彈跳視窗狀態
let schoolDialog = ref(false); // 據點
let courseDialog = ref(false); // 課程
let studentListDialog = reactive([]); // 學習者名單
let enrolledDialog = reactive([]); // 出席清單
let sessionsDialog = ref(false); // 場次

// watch(schoolDialog, () => {
//   initMap();
// });

// 據點參數
let location = reactive({
  location_name: "",
  Lng: "",
  Lat: "",
  address: "",
  introduction: "",
  email: "",
  phone: "",
  access_token: token,
});

// // Google Map
// const states = reactive({
//   google: null,
//   map: null,
//   markers: null,
// });

// const initMap = async () => {
//   const loader = new Loader({
//     apiKey: "AIzaSyClxiB7zcQDyGaB1r3Ww_VQG950AtjVoAk",
//     version: "weekly",
//     libraries: ["places"],
//     language: "zh-TW",
//   });
//   states.google = await loader.load();
//   let dom = document.getElementById("map");
//   states.map = new states.google.maps.Map(document.getElementById("map"), {
//     center: { lat: 25.0425, lng: 121.5468 },
//     zoom: 11,
//     mapTypeControl: false,
//     fullscreenControl: false,
//   });
// };

// // 查詢 Google 地圖
// const getCoordinates = async () => {
//   const geocoder = new states.google.maps.Geocoder();
//   geocoder.geocode({ address: location.address }, (results, status) => {
//     if (status === states.google.maps.GeocoderStatus.OK) {
//       location.Lat = results[0].geometry.location.lat();
//       location.Lng = results[0].geometry.location.lng();
//     }

//     // 將地圖中心設為取得的經緯度，並調整縮放等級
//     states.map.setCenter({ lat: location.Lat, lng: location.Lng });
//     states.map.setZoom(15);

//     // 設定地址圖標
//     const marker = new google.maps.Marker({
//       position: { lat: location.Lat, lng: location.Lng },
//       map: states.map,
//       title: location.address,
//       icon: store.getImageUrl("map-icon/icon_house05.png"),
//     });
//   });
// };

// 更新按鈕狀態
// function updateButtonStatus(name) {
//   if (name === "location") {
//     saveLoading.value = false;
//     locationBtnText.value = "儲存成功！";
//     setTimeout(() => {
//       // schoolDialog.value = false; // 關閉彈跳視窗
//       locationBtnText.value = "儲存";
//     }, 3000);
//   } else if (name === "course") {
//     courseBtnLoading.value = false;
//     courseBtnText.value = "儲存成功！";
//     setTimeout(() => {
//       // courseDialog.value = false; // 關閉彈跳視窗
//       courseBtnText.value = "儲存";
//     }, 3000);
//   }
// }

let schoolData = reactive({});
let locationId = ref(null);

// 取得據點
async function getSchool(id) {
  console.log("getSchool id", id);
  locationId.value = id;

  try {
    const response = await axios.get(
      // `${store.apiUrl}/api/get_school?location_id=${id}&access_token=${token}` // 暫時不帶 token
      `${store.apiUrl}/api/get_school?location_id=${id}`
    );
    schoolData = response.data.schools[0];
    console.log("據點", schoolData);
    for (const key in schoolData) {
      if (location.hasOwnProperty(key) && schoolData[key] !== undefined) {
        location[key] = schoolData[key];
      }
      if (key === "school_introduction") {
        location["introduction"] = schoolData["school_introduction"];
      }
    }

    // 設定地圖
    // getCoordinates();
  } catch (error) {
    console.error(error);
  }
}

// 儲存按鈕狀態
let saveLoading = ref(false);
// let locationBtnText = ref("儲存修改");

// 更新據點
async function saveLocation() {
  saveLoading.value = true;
  let data = reactive({
    location_id: locationId.value,
    location_name: "",
    Lng: "",
    Lat: "",
    address: "",
    introduction: "",
    email: "",
    phone: "",
  });

  for (const key in location) {
    if (data.hasOwnProperty(key) && location[key] !== undefined) {
      data[key] = location[key];
    }
  }

  const formData = new FormData();
  for (const key in data) {
    formData.append(key, data[key]);
  }

  try {
    await axios.post(`${store.apiUrl}/api/update_school`, formData);

    setTimeout(() => {
      saveLoading.value = false;
      store.setAlert("儲存成功");
    }, 1000);

    // setTimeout(() => {
    //   updateButtonStatus("location");
    // }, 500);
  } catch (error) {
    console.error(error);
  }
}

// 課程參數
let course = reactive({
  name: "", // 課程名稱
  location_id: "", // 據點編號
  category: "", // 工藝類別
  introduction: "", // 課程簡介
  organizer: "", // 主辦單位
  cover_img_file: "", // 課程圖片
  group_id: 2, // 學群編號(技藝)
  group_sort: "", // 學群細分
  special_class_list_name: "",
  recommend: 0, // 是否推薦
  is_inner: 1, // 內課課程
  is_check: 0, // 審核結果
  address: "", // 上課地點
  access_token: token,
});

let classNameId = ref(null);
let courseLoading = ref(false);
let coverImgLoading = ref(false);
let enCode = ref(null);

// 取得課程
async function getCourse(id) {
  classNameId.value = id;
  console.log("取得課程", id);
  courseLoading.value = true;

  let token = store.token;

  try {
    let response = await axios.get(
      `${store.apiUrl}/api/get_class_name?class_name_id=${id}&access_token=${token}`
    );

    // console.log('課程資料',response);
    courses.list = response.data.classes;
    console.log("課程資料", courses.list);
    let coursesData = response.data.classes[0];
    enCode.value = coursesData.encode;
    console.log("coursesData", coursesData);
    // classNameId.value = coursesData.class_name_id;

    // 存入課程資料
    for (const key in coursesData) {
      if (course.hasOwnProperty(key) && coursesData[key] !== undefined) {
        course[key] = coursesData[key];
      }

      if (coursesData["cover_img"] !== "") {
        coverImgLoading.value = true;
        coverImgUrl.value = `${store.imgUrl}/${coursesData["cover_img"]}`;

        setTimeout(() => {
          coverImgLoading.value = false;
        }, 1500);
      }
    }

    console.log("最終 course", course);

    loading.value = false;
  } catch (error) {
    console.error(error);
  }
}

// 儲存按鈕狀態
let courseBtnLoading = ref(false);
// let courseBtnText = ref("儲存修改");

// 更新課程
async function saveCourse() {
  courseBtnLoading.value = true;
  delete course.access_token;

  course["class_name_id"] = classNameId.value;
  if (coverImg.value) {
    course["cover_img_file"] = coverImg.value;
  }

  const formData = new FormData();
  for (const key in course) {
    formData.append(key, course[key]);
  }

  try {
    await axios.post(`${store.apiUrl}/api/update_class_name`, formData);

    setTimeout(() => {
      saveLoading.value = false;
      store.setAlert("儲存成功");
    }, 1000);

    // setTimeout(() => {
    //   updateButtonStatus("course");
    // }, 500);
  } catch (error) {
    console.error(error);
  }
}

// 上傳圖片 Input
const coverImgRef = ref(null);

const fileInputClick = (ref) => {
  if (ref === "cover") {
    if (coverImgRef.value) {
      coverImgRef.value[0].click();
    }
  }
};

// 封面圖片
let coverImg = ref("");
let coverImgUrl = ref("");

const handleCoverImg = (event) => {
  const file = event.target.files[0];
  if (file) {
    coverImg.value = file;
    coverImgUrl.value = URL.createObjectURL(file); // 設定圖片預覽 URL
  }
};

// 取得所有課堂
async function getAllSession(id) {
  console.log("getAllSession id", id);

  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_session?event_id=${id}`
    );
    session.list = response.data.classe_sessions;
    console.log("課堂資料", session.list);
  } catch (error) {
    console.error(error);
  }
}

// 取得場次
async function getEvent(id) {
  console.log("getEvent id", id);

  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_event?class_name_id=${id}`
    );
    // event_id
    console.log("場次資料", response);
    let eventId = response.data.classes[0].event_id;
    getAllSession(eventId);
    getEnrolledData(eventId);
  } catch (error) {
    console.error(error);
  }
}

let enrolledLoading = ref(false);

// 審核狀態
let registrationState = ref(false);

// 待審核報名清單
let pendingRegistration = reactive({
  list: [],
});

// 已審核報名清單
let approvedRegistration = reactive({
  list: [],
});

// 取得所有報名清單
async function getEnrolledData(eventId) {
  enrolledLoading.value = true;
  console.log("getEnrolledData eventId", eventId);

  const formData = new FormData();
  formData.append("class_id", eventId);

  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_registration_class?event_id=${eventId}&access_token=${token}`
    );
    const recordResponse = await axios.post(
      `${store.apiUrl}/api/add_attend_record_by_event`,
      formData
    );
    console.log("取得報名", response);
    console.log("新增課堂報名資料", recordResponse);

    pendingRegistration.list = response.data.registrations.filter(
      (item) => item.reg_confirm === 0
    );

    if (pendingRegistration.list.length) {
      registrationState.value = true;
    } else {
      registrationState.value = false;
    }

    // approvedRegistration.list = response.data.registrations.filter(
    //   (item) => item.reg_confirm === 1
    // );

    approvedRegistration.list = response.data.registrations;

    console.log("學員清單", approvedRegistration.list);

    approvedRegistration.list.map((item) => {
      if (item.payment_status) {
        item.payment_status = true;
      } else {
        item.payment_status = false;
      }
    });

    setTimeout(() => {
      enrolledLoading.value = false;
    }, 1000);
  } catch (error) {
    console.error(error);
  }
}

let fiveDigitsInput = ref([]); // 是否輸入末五碼
let showChip = ref([]);

// 更新報名清單
async function updateEnrolledData(item, index) {
  console.log("更新報名清單", item);

  const data = {
    is_attend: item.is_attend,
    payment_status: item.payment_status ? 1 : 0,
    reg_confirm: item.reg_confirm,
    five_digits: item.five_digits ? item.five_digits : "00000",
  };

  // 若取消付款狀態則清空末五碼欄位
  if (!data.payment_status) {
    data.five_digits = "00000";
    approvedRegistration.list[index].five_digits = "";
  }

  console.log("data >", data);
  const formData = new FormData();
  for (const key in data) {
    formData.append(key, data[key]);
  }

  try {
    const response = await axios.post(
      `${store.apiUrl}/api/update_registration_class?event_id=${item.event_id}&user_id=${item.user_id}&access_token=${token}`,
      formData
    );
    console.log("更新", response);

    fiveDigitsInput.value = [];
    showChip.value[index] = true;

    setTimeout(() => {
      showChip.value[index] = false;
    }, 2000);
  } catch (error) {
    console.error(error);
  }
}

// 場次
let eventData = reactive({
  list: [],
});

// 場次參數
let event = reactive({
  id: "", // 場次 ID
  name_id: "", // 課程 ID
  event: "", // 場次名稱
  start_time: "", // 課程起始日
  end_time: "", // 課程結束日
  contact: "", // 聯絡資訊
  lecturer: "", // 課程講師
  location: "",
  content: "", // 課程內容
  URL: "", // 外部連結
  people: "", // 對象
  fee_method: "", // 課程價格
  fee_payment: "", // 收費方式
  registration_way: "", // 報名方式
  registration_start: "", // 報名起始日
  registration_end: "", // 報名截止日
  number_limit: "", // 人數限制
  number_minimum: "", // 最低開課人數
  remark: "", // 備註
  ATM_address: "", // 匯款帳號(銀行代碼+帳號)
  // files: [], // 課程檔案(若無檔案則不需送此欄位)
  access_token: token,
});

let eventType = ref(""); // 課程類型
let isOneDay = ref(null); // 是否為一日課程

watch(eventType, (val) => {
  console.log("eventType", val);
  if (
    val ===
    `${t("form.periodic_courses")}（e.g., 2023/10/1～2023/10/30 ${t(
      "form.classes_schedule"
    )}）`
  ) {
    isOneDay.value = false;
  } else {
    isOneDay.value = true;
    date.end_date = date.start_date;
  }
});

let isRemit = ref(false); // 是否顯示匯款資訊欄位
let bankCode = ref(""); // 銀行代碼
let bankAccount = ref(""); // 銀行帳號

watch(event, (data) => {
  if (data.fee_payment === "匯款") {
    isRemit.value = true;
  } else {
    isRemit.value = false;
  }
});

let date = reactive({
  start_date: "", // 起始日期
  start_time: "", // 起始時間
  end_date: "", // 結束日期
  end_time: "", // 結束時間
  registration_start_date: "", // 報名起始日期
  registration_start_time: "", // 報名起始時間
  registration_end_date: "", // 報名截止日期
  registration_end_time: "", // 報名截止時間
});

// 取得場次(編輯)
async function editEvent(id) {
  console.log("editEvent", id);
  event.name_id = id;

  let url = `${store.apiUrl}/api/get_event?class_name_id=${id}`;

  try {
    const response = await axios.get(url);
    const classes = response.data.classes[0];
    event.id = classes.event_id;

    // 存入場次資料
    for (const key in classes) {
      if (event.hasOwnProperty(key) && classes[key] !== undefined) {
        event[key] = classes[key];
      }

      // 處理時間
      if (key === "start_time") {
        date.start_time = dateToObject(classes[key]);
        date.start_date = store.convertUTCtoTaiwanTime(classes[key]);
      }

      if (key === "end_time") {
        console.log("date.end_date !!!", date.end_date);
        date.end_time = dateToObject(classes[key]);
        date.end_date = store.convertUTCtoTaiwanTime(classes[key]);
      }

      if (key === "registration_start") {
        date.registration_start_time = dateToObject(classes[key]);
        date.registration_start_date = store.convertUTCtoTaiwanTime(
          classes[key]
        );
      }

      if (key === "registration_end") {
        date.registration_end_time = dateToObject(classes[key]);
        date.registration_end_date = store.convertUTCtoTaiwanTime(classes[key]);
      }
    }
    getAssignSession(event.id); // 取得課堂
  } catch (error) {
    console.error(error);
  }
}

// 將時間字串轉為物件 (vue-datepicker格式)
function dateToObject(dateString) {
  const date = new Date(dateString);
  const hours = date.getUTCHours();
  const minutes = date.getUTCMinutes();
  const seconds = date.getUTCSeconds();

  return { hours, minutes, seconds };
}

let studentDialog = ref(false);
let record = reactive({
  list: [],
});

// 場次資訊
const weekList = reactive(["一", "二", "三", "四", "五", "六", "日"]);
const selectedWeek = ref([0, 0, 0, 0, 0, 0, 0]); // 選擇星期

const toggleSelected = (index) => {
  if (selectedWeek.value[index]) {
    selectedWeek.value[index] = 0;
  } else {
    selectedWeek.value[index] = 1;
  }
};

let sessionTime = reactive({
  start_week_time: [],
  end_week_time: [],
});

let sessionStartTimeList = ref(["", "", "", "", "", "", ""]);
let sessionEndTimeList = ref(["", "", "", "", "", "", ""]);

// 取得課堂
async function getAssignSession(eventId) {
  console.log("getAssignSession", eventId);

  let url = `${store.apiUrl}/api/get_session?event_id=${eventId}`;

  try {
    const response = await axios.get(url);
    if (response.data.data_form === "one day class") {
      isOneDay.value = true;
      eventType.value = `${t("form.one_day_courses")}（e.g., 2023/10/1 ${t(
        "form.classes_monday"
      )}）`;
    } else {
      isOneDay.value = false;
      eventType.value = `${t(
        "form.periodic_courses"
      )}（e.g., 2023/10/1～2023/10/30 ${t("form.classes_schedule")}）`;

      selectedWeek.value = response.data.data_form.week_day;

      // 週期起始時間
      sessionTime.start_week_time = convertTimeArrays(
        response.data.data_form.start_week_time
      );

      // 週期結束時間
      sessionTime.end_week_time = convertTimeArrays(
        response.data.data_form.end_week_time
      );
    }
  } catch (error) {
    console.error(error);
  }
}

// 若為一日課程則起始日期 = 結束日期
watch(date, (val) => {
  if (isOneDay.value && val.start_date) {
    date.end_date = val.start_date;
  }
});

// 轉換週期時間格式
function convertTimeArrays(timeArrays) {
  return timeArrays.map((timeString) => {
    if (timeString === null) {
      return null;
    }

    const [hours, minutes] = timeString.split(":").map(Number);

    return {
      hours,
      minutes,
      seconds: 0,
    };
  });
}

// 更新課堂
async function updateSession() {
  console.log("更新課堂");
  // 一日課程(課堂資訊)
  let oneDayData = {
    class_event_id: event.id,
    start_time: event.start_time,
    end_time: event.end_time,
    content: "",
  };

  console.log("oneDayData", oneDayData);

  // 週期課程(課堂資訊)
  const weekString = `[${selectedWeek.value.join(",")}]`;
  session.week_day_str = weekString;

  console.log("weekString", weekString);

  selectedWeek.value.map((item, index) => {
    if (item) {
      console.log("index", index);
      // 開始時間
      sessionStartTimeList.value[index] = `"${
        sessionTime.start_week_time[index].hours < 10 ? "0" : ""
      }${sessionTime.start_week_time[index].hours}:${
        sessionTime.start_week_time[index].minutes === 0
          ? "00"
          : sessionTime.start_week_time[index].minutes
      }:00"`;

      // 結束時間
      sessionEndTimeList.value[index] = `"${
        sessionTime.end_week_time[index].hours
      }:${
        sessionTime.end_week_time[index].minutes === 0
          ? "00"
          : sessionTime.end_week_time[index].minutes
      }:00"`;
    } else {
      sessionStartTimeList.value[index] = '""';
      sessionEndTimeList.value[index] = '""';
    }
  });

  session.start_week_time = `[${sessionStartTimeList.value}]`;
  session.end_week_time = `[${sessionEndTimeList.value}]`;
  session.class_event_id = event.id;

  console.log("session", session);

  try {
    if (isOneDay.value) {
      const oneDayFormData = new FormData();
      for (const key in oneDayData) {
        oneDayFormData.append(key, oneDayData[key]);
      }

      // 一日課程
      const response = await axios.post(
        `${store.apiUrl}/api/insert_session`,
        oneDayFormData
      );
      console.log("新增課堂(一日) response", response);
    } else {
      const formData = new FormData();
      for (const key in session) {
        formData.append(key, session[key]);
      }

      // 週期課程
      const response = await axios.post(
        `${store.apiUrl}/api/auto_create_session`,
        formData
      );
      console.log("新增課堂(週期) response", response);
    }
  } catch (error) {
    console.error(error);
  }
}

let dateReminder = ref(false);

// 更新場次
async function updateEvent() {
  console.log("date", date);

  let isSame = store.isSameDay(date.start_date, date.end_date);
  // 起始日期不可等於結束日期(週期課程)
  if (!isOneDay.value && isSame) {
    dateReminder.value = true;
    return;
  }
  dateReminder.value = false;
  saveLoading.value = true;

  // 處理時間格式
  event.start_time = store.mergeAndFormatDateTime(
    date.start_date,
    date.start_time
  );
  event.end_time = store.mergeAndFormatDateTime(date.end_date, date.end_time);
  event.registration_start = store.mergeAndFormatDateTime(
    date.registration_start_date,
    date.registration_start_time
  );
  event.registration_end = store.mergeAndFormatDateTime(
    date.registration_end_date,
    date.registration_end_time
  );
  console.log("date.registration_start_date", date.registration_start_date);
  console.log("date.registration_start_time", date.registration_start_time);
  console.log("event.registration_start", event.registration_start);
  console.log("event.registration_end", event.registration_end);
  console.log("event", event);

  let url = `${store.apiUrl}/api/update_event`;

  const formData = new FormData();
  for (const key in event) {
    formData.append(key, event[key]);
  }

  try {
    const response = await axios.post(url, formData);
    await updateSession();

    setTimeout(() => {
      saveLoading.value = false;
      store.setAlert("儲存成功");
    }, 1000);

    console.log("更新場次", response);
  } catch (error) {
    console.error(error);
  }
}

// 取得課堂出席名單
async function getAttendRecord() {
  // studentDialog.value = true;

  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_attend_record?class_detail_id=${sessionId.value}`
    );

    // 排除未審核學習者 reg_confirm = false
    // record.list = response.data.attend_record_list.filter(
    //   (item) => item.reg_confirm
    // );

    record.list = response.data.attend_record_list;
    console.log("報名清單", record.list);

    record.list.map((item) => {
      console.log("item.is_attend", item, item.is_attend);
      if (item.is_attend) {
        item.is_attend = true;
      } else {
        item.is_attend = false;
      }
    });
  } catch (error) {
    console.error(error);
  }
}

// 更新課堂出席名單
async function saveAttendRecord(item) {
  const data = {
    id: item.raw.id,
    class_detail_id: item.raw.class_detail_id,
    user_id: item.raw.user_id,
    is_attend: item.raw.is_attend ? 1 : 0,
  };

  const formData = new FormData();
  for (const key in data) {
    formData.append(key, data[key]);
  }

  console.log("data", data);

  try {
    const response = await axios.get(
      `${store.apiUrl}/api/update_attend_record?id=${data.id}&class_detail_id=${data.class_detail_id}&user_id=${data.user_id}&is_attend=${data.is_attend}`
    );

    if (response.data.msg === "success") {
      alert("更新成功！");
    }
    console.log("更新報名清單", response);
  } catch (error) {
    console.error(error);
  }
}

let sessionId = ref(null);
let session = reactive({
  list: [],
});

// 選擇日期後顯示出席名單
watch(sessionId, (val) => {
  if (val) {
    getAttendRecord();
  }
});

let tab = ref(2);

async function updateRegConfirm(item) {
  console.log("updateRegConfirm", item);

  const data = {
    is_attend: item.is_attend,
    payment_status: 0,
    reg_confirm: 1, // 審核確認
    five_digits: "00000",
  };

  const formData = new FormData();
  for (const key in data) {
    formData.append(key, data[key]);
  }

  try {
    const response = await axios.post(
      `${store.apiUrl}/api/update_registration_class?event_id=${item.event_id}&user_id=${item.user_id}&access_token=${token}`,
      formData
    );

    console.log("更新審核", response);
    sessionId.value = null; // 審核後需重新選擇出席管理日期
    record.list = []; // 清空出席名單
    getEnrolledData(item.event_id);
  } catch (error) {
    console.error(error);
  }
}

let itemsPerPage = ref(10); // 每頁顯示筆數(查看出缺席)

let pendingHeaders = reactive([
  {
    title: "姓名",
    key: "real_name",
  },
  { title: "電話", key: "phone" },
  { title: "信箱", key: "email" },
  { title: "審核", key: "reg_confirm" },
]);

let approvedHeaders = reactive([
  {
    title: "姓名",
    key: "real_name",
  },
  { title: "電話", key: "phone" },
  { title: "信箱", key: "email" },
  { title: "付款狀態", key: "payment" },
  { title: "末五碼", key: "five_digits" },
]);

let studentHeaders = reactive([
  {
    title: "姓名",
    align: "start",
    key: "real_name",
  },
  { title: "電話", key: "phone" },
  { title: "信箱", key: "email" },
  { title: "出席", key: "is_attend" },
]);

let assignTag = ref("all");
// let isInternal = ref(false); // 是否選取學習時數課程(只顯示內課)

// watch(assignTag, (val) => {
//   console.log("val", val);
//   if (val === "all") {
//     isInternal.value = false;
//   } else {
//     isInternal.value = true;
//   }
//   // pageNum.value = 1;
//   // getClass();
// });

function selectTag(btn) {
  pageNum.value = 1;
  if (btn === "all") {
    isCheck.value = null;
    assignTag.value = "all";
  } else {
    isCheck.value = btn;
    assignTag.value = btn;
  }

  getClass();

  console.log("assignTag.value", assignTag.value);
}

// 開課搜尋
async function search() {
  if (searchInput.value === "" || searchInput.value === null) {
    searchState.value = false;
    getClass();
    return;
  }

  searchState.value = true;

  let url = `${store.apiUrl}/api/get_class_name?access_token=${token}&page_num=1&page_amount=${pageAmount.value}&keyword=${searchInput.value}`;

  if (isCheck.value) {
    url += `&is_check=${isCheck.value}`;
  }

  try {
    let response = await axios.get(url);
    classes.list = response.data.classes;

    totalPages.value = store.getTotalPages(response.data.total_num, 5);

    console.log("totalPages.value", totalPages.value);

    setTimeout(() => {
      loading.value = false;
    }, 500);

    console.log("開課資料", classes.list);
  } catch (error) {
    console.error(error);
  }

  console.log("url", url);
  console.log("searchInput", searchInput.value);
}

// 課程重新審核
async function resubmit(index) {
  course.is_check = 0;
  course["class_name_id"] = index;
  console.log("resubmit course", course);

  let url = `${store.apiUrl}/api/update_class_name`;

  const formData = new FormData();
  for (const key in course) {
    formData.append(key, course[key]);
  }

  try {
    const response = await axios.post(url, formData);
    console.log("重新審核", response);
    store.setAlert("申請已送出");
    // alert("申請已送出！點擊確認後將重新整理頁面。");
    window.location.reload();
  } catch (error) {
    console.error(error);
  }
}

// 關閉課程
async function closeClass(id) {
  console.log("close id", id);
  console.log("token", token);

  let url = `${store.apiUrl}/api/close_class?class_name_id=${id}&access_token=${token}`;

  try {
    const response = await axios.post(url);
    console.log("關閉課程", response);
    store.setAlert("課程已關閉");
    // alert("課程已關閉！點擊確認後將重新整理頁面。");
    window.location.reload();
  } catch (error) {
    console.error(error);
  }
}
</script>

<template>
  <v-card class="h-100 user-courses">
    <div ref="title" class="title">
      <h4>{{ t("navbar.courses") }}</h4>
    </div>

    <div
      class="d-flex flex-column flex-sm-row align-start align-sm-center ms-auto search-item"
    >
      <v-text-field
        @keyup.enter="search()"
        v-model="searchInput"
        :label="t('search_courses')"
        variant="outlined"
        density="compact"
        hide-details
        clearable
      ></v-text-field>

      <button @click="search()" class="ms-2">
        <img
          src="@/assets/img/news/news-search-icon.png"
          alt="臺灣工藝學習平台"
        />
      </button>
    </div>

    <!-- <div class="search flex-row align-center">
     

      <span>
        <input
          v-model="searchInput"
          type="text"
          @keyup.enter="search()"
          :placeholder="t('keyword_search')"
        />
        <button @click="search()">
          <img
            src="@/assets/img/news/news-search-icon.png"
            alt="臺灣工藝學習平台"
          />
        </button>
      </span>
      <small class="ms-3">清除</small>
    </div> -->

    <div
      class="d-flex flex-column flex-sm-row justify-center tab-btn mt-5"
    >
      <v-btn
        variant="text"
        @click="selectTag('all')"
        :class="{ active: assignTag === 'all' }"
      >
        {{ t("all") }}
      </v-btn>
      <v-btn
        variant="text"
        @click="selectTag('0')"
        :class="{ active: assignTag === '0' }"
      >
        {{ t("awaiting_approval") }}
      </v-btn>
      <v-btn
        variant="text"
        @click="selectTag('1')"
        :class="{ active: assignTag === '1' }"
      >
        {{ t("approved") }}
      </v-btn>
      <v-btn
        variant="text"
        @click="selectTag('2')"
        :class="{ active: assignTag === '2' }"
      >
        {{ t("rejected") }}
      </v-btn>
      <v-btn
        variant="text"
        @click="selectTag('3')"
        :class="{ active: assignTag === '3' }"
      >
        {{ t("closed") }}
      </v-btn>
    </div>

    <div class="d-flex justify-center my-10" v-if="loading">
      <v-progress-circular
        color="grey-lighten-4"
        indeterminate
      ></v-progress-circular>
    </div>

    <div v-else-if="!loading && classes.list.length" class="main-table">
      <!-- <h6 class="table-title">開課紀錄</h6> -->
      <!-- <router-link
        v-if="!classes.list.length && isCheck !== '2' && isCheck !== '3'"
        to="/setup-courses"
        class="hint-item mb-7"
        >點此進入開課專區</router-link
      > -->
      <table>
        <thead>
          <tr>
            <th></th>
            <th width="30%">{{ t("name") }}</th>
            <th>{{ t("form.course_create") }}</th>
            <th width="20%">{{ t("form.course_state") }}</th>
            <th width="150px">{{ t("form.management") }}</th>
            <th width="100px"></th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in classes.list" :key="index">
            <td>
              <v-chip v-if="item.is_pass_proposal === 0">
                {{ t("proposal_awaiting_approval") }}
              </v-chip>

              <v-chip v-if="item.is_pass_proposal === 1 && item.is_check === 0">
                {{ t("awaiting_approval") }}
              </v-chip>
              <v-chip
                v-else-if="item.is_check === 1"
                color="green"
                text-color="white"
              >
                {{ t("approved") }}
              </v-chip>

              <v-chip
                v-else-if="item.is_check === 2"
                color="error"
                text-color="white"
              >
                {{ t("rejected") }}
              </v-chip>

              <v-chip
                v-else-if="item.is_check === 3"
                variant="flat"
                color="grey-darken-1"
              >
                {{ t("closed") }}
              </v-chip>
            </td>
            <td>{{ item.name }}</td>
            <td>
              {{ moment(`${item.create_time}`).format("YYYY/MM/DD") }}
            </td>
            <td>
              <!-- 課程狀態 -->
              <span>{{ item.state }}</span>
            </td>
            <td>
              <div class="d-flex flex-column justify-center">
                <v-menu>
                  <template v-slot:activator="{ props }">
                    <div class="d-flex flex-column">
                      <v-btn
                        v-bind="props"
                        color="purple"
                        variant="outlined"
                        :disabled="item.is_check === 3"
                      >
                        <p>{{ t("form.course_management") }}</p>
                      </v-btn>
                    </div>
                  </template>
                  <v-list>
                    <v-list-item v-if="item.is_check !== 2">
                      <v-list-item-title>
                        <v-btn
                          variant="text"
                          @click="getSchool(item.location_id)"
                        >
                          {{ t("form.edit_location") }}
                          <v-dialog
                            v-model="schoolDialog"
                            activator="parent"
                            width="600"
                          >
                            <v-card class="pa-5">
                              <v-card-title class="ps-5 pb-5">
                                {{ t("form.edit_location") }}
                              </v-card-title>
                              <v-card-text>
                                <v-label
                                  class="d-flex flex-column flex-sm-row align-start align-sm-center pb-3"
                                >
                                  <p class="pb-5 pe-3">
                                    {{ t("form.location_name") }}
                                    <span class="mark">*</span>
                                  </p>
                                  <v-text-field
                                    v-model="location.location_name"
                                    :rules="[requiredRule]"
                                    :placeholder="t('form.provide_name')"
                                    density="compact"
                                    variant="outlined"
                                    counter
                                    maxlength="60"
                                  ></v-text-field>
                                </v-label>

                                <v-label
                                  class="d-flex flex-column flex-sm-row align-start align-sm-center pb-3 w-100"
                                >
                                  <p class="pb-5 pe-3">
                                    {{ t("form.location_address") }}
                                    <span class="mark">*</span>
                                  </p>
                                  <v-text-field
                                    v-model="location.address"
                                    :rules="[requiredRule]"
                                    density="compact"
                                    variant="outlined"
                                    :placeholder="
                                      t('form.safe_accessible_location')
                                    "
                                  ></v-text-field>
                                  <!-- <v-btn
                                  @click="getCoordinates"
                                  color="purple"
                                  variant="flat"
                                  class="ms-3 mb-6 px-8"
                                >
                                  查詢
                                </v-btn> -->
                                </v-label>

                                <!-- <div
                                class="d-flex flex-column justify-end ms-16 ps-5"
                              >
                                <div
                                  class="map"
                                  id="map"
                                  style="width: 100%; height: 31.25em"
                                ></div>

                                <v-row class="mt-3">
                                  <v-col cols="12" md="6">
                                    <v-label class="d-flex align-center">
                                      <p class="pb-5 pe-3">經度</p>
                                      <v-text-field
                                        v-model="location.Lng"
                                        density="compact"
                                        variant="outlined"
                                        disabled
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>
                                  <v-col cols="12" md="6">
                                    <v-label class="d-flex align-center">
                                      <p class="pb-5 pe-3">緯度</p>
                                      <v-text-field
                                        v-model="location.Lat"
                                        density="compact"
                                        variant="outlined"
                                        disabled
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>
                                </v-row>
                              </div> -->

                                <v-label class="d-block">
                                  <p class="d-flex mb-5">
                                    {{ t("form.location_email") }}
                                    <span class="mark">*</span>
                                  </p>
                                  <v-text-field
                                    v-model="location.email"
                                    :rules="[requiredRule]"
                                    density="compact"
                                    variant="outlined"
                                    placeholder="請填寫 Email"
                                  ></v-text-field>
                                </v-label>

                                <v-label class="d-block mt-3">
                                  <p class="d-flex">
                                    {{ t("form.location_phone") }}
                                    <span class="mark">*</span>
                                  </p>
                                  <span class="d-block pt-1 pb-3 hint">
                                    {{ t("form.display_on_course_intro") }}
                                  </span>
                                  <v-text-field
                                    v-model="location.phone"
                                    :rules="[requiredRule]"
                                    density="compact"
                                    variant="outlined"
                                    :placeholder="
                                      t('form.enter_telephone_number')
                                    "
                                  ></v-text-field>
                                </v-label>

                                <v-label class="d-block mt-3">
                                  <p class="d-flex mb-5">
                                    {{ t("form.location_introduction") }}
                                    <span class="mark">*</span>
                                  </p>
                                  <v-textarea
                                    v-model="location.introduction"
                                    rows="5"
                                    variant="outlined"
                                    placeholder="請輸入工坊簡介"
                                    hint="文字長度不得低於 50 個字元，最多 150 個字元"
                                    maxlength="150"
                                    counter
                                    :rules="[
                                      (value) =>
                                        (value && value.length >= 50) ||
                                        '請至少輸入 50 個字元，以確保內容完整性',
                                    ]"
                                  ></v-textarea>
                                </v-label>
                              </v-card-text>
                              <v-card-actions class="d-flex justify-center">
                                <v-btn
                                  variant="outlined"
                                  color="purple"
                                  @click="schoolDialog = false"
                                  class="me-2 px-3"
                                  >{{ t("form.cancel") }}</v-btn
                                >
                                <v-btn
                                  variant="flat"
                                  color="purple"
                                  class="px-6"
                                  :loading="saveLoading"
                                  @click="saveLocation()"
                                  >{{ t("form.save") }}</v-btn
                                >
                              </v-card-actions>
                            </v-card>
                          </v-dialog>
                        </v-btn>
                      </v-list-item-title>
                    </v-list-item>

                    <v-list-item>
                      <v-list-item-title>
                        <!-- {{ item.title }} -->

                        <v-btn
                          @click="getCourse(item.class_name_id)"
                          variant="text"
                        >
                          {{ t("form.edit_course") }}
                          <v-dialog
                            v-model="courseDialog"
                            activator="parent"
                            width="600"
                          >
                            <v-card class="pa-5">
                              <v-card-title class="ps-5 pb-8">
                                {{ t("form.edit_course") }}
                              </v-card-title>
                              <v-card-text class="mb-7">
                                <v-row class="justify-space-evenly">
                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block pb-3">
                                      <p class="pb-5 pe-3">
                                        {{ t("form.course_number") }}
                                      </p>
                                      <v-text-field
                                        v-model="enCode"
                                        density="compact"
                                        variant="outlined"
                                        disabled
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>

                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block pb-3">
                                      <p class="pb-5 pe-3">
                                        {{ t("form.course_name") }}
                                        <span class="mark">*</span>
                                      </p>
                                      <v-text-field
                                        v-model="course.name"
                                        :rules="[requiredRule]"
                                        density="compact"
                                        variant="outlined"
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>

                                  <!-- <v-col cols="12" md="6">
                                  <v-label class="d-block pb-3">
                                    <p class="pb-5 pe-3">
                                      課程價格<span class="mark">*</span>
                                    </p>
                                    <v-text-field
                                      :rules="[requiredRule]"
                                      density="compact"
                                      variant="outlined"
                                    ></v-text-field>
                                  </v-label>
                                </v-col> -->

                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block pb-3">
                                      <p class="pb-5 pe-3">
                                        {{ t("form.craft_category") }}
                                        <span class="mark">*</span>
                                      </p>
                                      <v-select
                                        v-model="course.category"
                                        placeholder="請選擇類別"
                                        :items="[
                                          '樹藝',
                                          '漆藝',
                                          '藍染',
                                          '蠟雕',
                                          '竹工藝',
                                          '金工/飾品',
                                          '蠟燭/香氛/調香',
                                          '植栽/花藝',
                                          '插畫/繪畫/寫字',
                                          '皮件/皮革',
                                          '木工/竹藝',
                                          '陶藝/玻璃',
                                          '編織/羊毛氈/縫紉',
                                          '其他',
                                        ]"
                                        :rules="[requiredRule]"
                                        density="compact"
                                        variant="outlined"
                                      ></v-select>
                                    </v-label>
                                  </v-col>

                                  <!-- <v-col cols="12" md="6">
                                  <v-label class="d-block pb-3">
                                    <p class="pb-5 pe-3">
                                      適合報名對象(年紀)<span class="mark"
                                        >*</span
                                      >
                                    </p>

                                    <v-select
                                      v-model="age"
                                      :items="[
                                        '不拘',
                                        '7 歲以下',
                                        '7-18 歲',
                                        '18-65 歲',
                                        '65 歲以上',
                                      ]"
                                      :rules="[requiredRule]"
                                      density="compact"
                                      variant="outlined"
                                      outlined
                                    ></v-select>
                                  </v-label>
                                </v-col> -->

                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block pb-3">
                                      <p class="pb-5 pe-3">
                                        {{ t("form.course_location") }}
                                      </p>
                                      <v-text-field
                                        v-model="course.address"
                                        density="compact"
                                        variant="outlined"
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>

                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block pb-3">
                                      <p class="pb-5 pe-3">
                                        {{ t("form.organizer") }}
                                      </p>
                                      <v-text-field
                                        v-model="course.organizer"
                                        density="compact"
                                        variant="outlined"
                                      ></v-text-field>
                                    </v-label>
                                  </v-col>

                                  <v-col cols="12" class="py-0">
                                    <v-label class="d-block">
                                      <p class="d-flex">
                                        {{ t("form.course_intro") }}
                                        <span class="mark">*</span>
                                      </p>
                                      <small class="d-block text-gray my-2">
                                        {{ t("form.content_requirements") }}
                                      </small>
                                      <v-textarea
                                        v-model="course.introduction"
                                        rows="5"
                                        variant="outlined"
                                        :rules="[
                                          (value) =>
                                            (value && value.length >= 50) ||
                                            '請至少輸入 50 個字元，以確保內容完整性',
                                        ]"
                                        counter
                                      ></v-textarea>
                                    </v-label>
                                  </v-col>

                                  <v-col cols="12" class="me-auto">
                                    <v-label class="d-block">
                                      <p class="d-flex">
                                        {{ t("form.cover_image") }}
                                        <span class="mark">*</span>
                                      </p>

                                      <v-file-input
                                        multiple
                                        v-model="coverImg"
                                        id="coverImgRef"
                                        ref="coverImgRef"
                                        label="File input"
                                        variant="outlined"
                                        :placeholder="t('form.choose_image')"
                                        @change="handleCoverImg"
                                        style="display: none"
                                      ></v-file-input>
                                    </v-label>

                                    <v-btn
                                      @click="fileInputClick('cover')"
                                      color="purple"
                                      class="my-5"
                                    >
                                      {{ t("form.choose_image") }}
                                    </v-btn>

                                    <div class="step-01 image-preview">
                                      <div
                                        class="d-flex justify-center"
                                        v-if="coverImgLoading"
                                      >
                                        <v-progress-circular
                                          color="grey-lighten-4"
                                          indeterminate
                                        ></v-progress-circular>
                                      </div>

                                      <img
                                        v-if="
                                          coverImgUrl !== '' && !coverImgLoading
                                        "
                                        :src="coverImgUrl"
                                        alt="上傳圖片預覽"
                                      />
                                    </div>
                                  </v-col>
                                </v-row>
                              </v-card-text>
                              <v-card-actions class="d-flex justify-center">
                                <v-btn
                                  variant="outlined"
                                  color="purple"
                                  @click="courseDialog = false"
                                  class="me-2 px-3"
                                  >{{ t("form.cancel") }}</v-btn
                                >
                                <v-btn
                                  variant="flat"
                                  color="purple"
                                  class="px-6"
                                  :loading="courseBtnLoading"
                                  @click="saveCourse()"
                                  >{{ t("form.save") }}</v-btn
                                >
                              </v-card-actions>
                            </v-card>
                          </v-dialog>
                        </v-btn>
                      </v-list-item-title>
                    </v-list-item>

                    <v-list-item>
                      <v-list-item-title>
                        <v-dialog width="800" v-model="sessionsDialog">
                          <template v-slot:activator="{ props }">
                            <v-btn
                              @click="editEvent(item.class_name_id)"
                              v-bind="props"
                              variant="text"
                              >{{ t("form.edit_session") }}
                            </v-btn>
                          </template>

                          <template v-slot:default="{ isActive }">
                            <v-card class="sessions-card pb-3">
                              <!-- <v-card-title>
                                <span class="d-block pa-8">編輯場次</span>
                              </v-card-title> -->
                              <v-card-text class="pa-3 pa-sm-8">
                                <v-form
                                  ref="eventForm"
                                  lazy-validation
                                  @submit.prevent
                                >
                                  <v-container class="py-0">
                                    <v-row>
                                      <v-col cols="12">
                                        <p
                                          class="text-h6 font-weight-bold my-3"
                                        >
                                          {{ t("form.edit_session") }}
                                        </p>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            {{ t("form.session_name") }}
                                            <span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.event"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                            placeholder="可與課程名稱相同"
                                          ></v-text-field>
                                        </v-label>
                                      </v-col>

                                      <!-- <v-col cols="12" sm="6" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            課程講師<span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.lecturer"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                          ></v-text-field>
                                        </v-label>
                                      </v-col> -->

                                      <!-- <v-col cols="12" sm="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            聯絡資訊<span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.contact"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                          ></v-text-field>
                                        </v-label>
                                      </v-col> -->

                                      <v-col cols="12" sm="6" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            {{ t("form.course_quota") }}
                                            <span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.number_limit"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                            type="number"
                                            hint="請設定報名人數上限"
                                          ></v-text-field>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            {{ t("form.minimum_enrollment") }}
                                            <span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.number_minimum"
                                            density="compact"
                                            variant="outlined"
                                            type="number"
                                            :placeholder="
                                              t('form.enter_minimum_enrollment')
                                            "
                                          ></v-text-field>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            {{ t("form.payment_method") }}
                                            <span class="mark">*</span>
                                          </p>

                                          <v-select
                                            v-model="event.fee_payment"
                                            :items="['現場收費', '匯款']"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                            outlined
                                          ></v-select>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          v-if="isRemit"
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            匯款資訊<span class="mark">*</span>
                                          </p>

                                          <div class="d-flex w-100">
                                            <v-text-field
                                              v-model="bankCode"
                                              label="銀行代碼"
                                              :rules="[requiredRule]"
                                              density="compact"
                                              variant="outlined"
                                              style="width: 30%"
                                              class="me-3"
                                            ></v-text-field>
                                            <v-text-field
                                              v-model="bankAccount"
                                              label="匯款帳號 (10-16 碼)"
                                              :rules="[requiredRule]"
                                              density="compact"
                                              variant="outlined"
                                              style="width: 70%"
                                            ></v-text-field>
                                          </div>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pe-3">
                                            {{ t("form.course_price")
                                            }}<span class="mark">*</span>
                                          </p>
                                          <v-text-field
                                            v-model="event.fee_method"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                            type="number"
                                          ></v-text-field>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-3 pe-3">
                                            {{ t("form.target_audience") }}
                                            <span class="mark pb-3 pb-sm-4"
                                              >*</span
                                            >
                                          </p>
                                          <v-textarea
                                            v-model="event.people"
                                            rows="2"
                                            variant="outlined"
                                            :placeholder="
                                              t('form.target_placeholder')
                                            "
                                            :rules="[requiredRule]"
                                          ></v-textarea>
                                        </v-label>
                                      </v-col>

                                      <v-col cols="12" class="py-0">
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center py-2"
                                        >
                                          <p class="pb-5 pb-sm-0 ps-sm-8 pe-5">
                                            {{ t("form.remarks") }}
                                          </p>
                                          <v-text-field
                                            v-model="event.remark"
                                            density="compact"
                                            variant="outlined"
                                            hide-details
                                          ></v-text-field>
                                        </v-label>
                                      </v-col>

                                      <v-divider class="my-10"></v-divider>

                                      <v-col cols="12" class="pt-0">
                                        <p
                                          class="text-h6 font-weight-bold mb-3"
                                        >
                                          {{ t("form.course_duration") }}
                                        </p>
                                      </v-col>

                                      <v-col
                                        cols="12"
                                        class="py-0 position-relative"
                                      >
                                        <v-label
                                          class="d-flex flex-column flex-sm-row align-start align-sm-center"
                                        >
                                          <p class="pb-3 pe-3">
                                            {{ t("form.course_type") }}
                                            <span class="mark pb-4">*</span>
                                          </p>
                                          <v-select
                                            v-model="eventType"
                                            :items="[
                                              `${t(
                                                'form.one_day_courses'
                                              )}（e.g., 2023/10/1 ${t(
                                                'form.classes_monday'
                                              )}）`,
                                              `${t(
                                                'form.periodic_courses'
                                              )}（e.g., 2023/10/1～2023/10/30 ${t(
                                                'form.classes_schedule'
                                              )}）`,
                                            ]"
                                            :rules="[requiredRule]"
                                            density="compact"
                                            variant="outlined"
                                            outlined
                                          ></v-select>
                                        </v-label>
                                      </v-col>

                                      <v-col
                                        v-if="!isOneDay"
                                        cols="12"
                                        class="d-flex py-0"
                                      >
                                        <p
                                          class="pt-1 pe-3"
                                          style="width: 100px"
                                        >
                                          重複週期<span class="mark pb-4"
                                            >*</span
                                          >
                                        </p>

                                        <ul class="week-list">
                                          <li
                                            v-for="(item, index) in weekList"
                                            :key="index"
                                            @click="toggleSelected(index)"
                                            :class="{
                                              active: selectedWeek[index],
                                            }"
                                            class="d-flex"
                                          >
                                            <button class="item">
                                              {{ item }}
                                            </button>

                                            <div
                                              v-if="selectedWeek[index]"
                                              class="d-flex w-100 ms-5"
                                            >
                                              <VueDatePicker
                                                v-model="
                                                  sessionTime.start_week_time[
                                                    index
                                                  ]
                                                "
                                                time-picker
                                              />
                                              <span
                                                class="d-flex flex-column flex-sm-row align-start align-sm-center mx-2"
                                                >～</span
                                              >
                                              <VueDatePicker
                                                v-model="
                                                  sessionTime.end_week_time[
                                                    index
                                                  ]
                                                "
                                                time-picker
                                              />
                                            </div>
                                          </li>
                                        </ul>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.start_date") }}
                                          <span class="mark">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.start_date"
                                          :min-date="new Date()"
                                          :enable-time-picker="false"
                                          :format="store.datePickerFormat"
                                          locale="cn"
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        ></VueDatePicker>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.start_time") }}
                                          <span class="mark">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.start_time"
                                          time-picker
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        />
                                      </v-col>

                                      <v-col
                                        cols="12"
                                        sm="6"
                                        class="date-item position-relative"
                                      >
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.end_date") }}
                                          <span class="mark">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.end_date"
                                          :min-date="new Date()"
                                          :enable-time-picker="false"
                                          :format="store.datePickerFormat"
                                          locale="cn"
                                          :disabled="
                                            isOneDay ||
                                            item.state !== '課程等待審核'
                                          "
                                        ></VueDatePicker>
                                        <span
                                          v-if="dateReminder"
                                          class="date-reminder text-error"
                                          >{{
                                            t("form.periodic_courses_note")
                                          }}</span
                                        >
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.end_time") }}
                                          <span class="mark">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.end_time"
                                          time-picker
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        />
                                      </v-col>

                                      <v-divider class="my-10"></v-divider>

                                      <v-col cols="12" class="pt-0">
                                        <p
                                          class="text-h6 font-weight-bold mb-3"
                                        >
                                          {{ t("form.registration_time") }}
                                        </p>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{
                                            t("form.registration_start_date")
                                          }}
                                          <span class="mark pb-4">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.registration_start_date"
                                          :enable-time-picker="false"
                                          :format="store.datePickerFormat"
                                          locale="cn"
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        ></VueDatePicker>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.registration_time") }}
                                          <span class="mark pb-4">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.registration_start_time"
                                          time-picker
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        />
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.registration_deadline") }}
                                          <span class="mark pb-4">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.registration_end_date"
                                          :enable-time-picker="false"
                                          :format="store.datePickerFormat"
                                          locale="cn"
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        ></VueDatePicker>
                                      </v-col>

                                      <v-col cols="12" sm="6" class="date-item">
                                        <p class="mb-5 mb-sm-0 pe-3">
                                          {{ t("form.registration_end_time") }}
                                          <span class="mark pb-4">*</span>
                                        </p>
                                        <VueDatePicker
                                          v-model="date.registration_end_time"
                                          time-picker
                                          :disabled="
                                            item.state !== '課程等待審核'
                                          "
                                        />
                                      </v-col>
                                    </v-row>
                                  </v-container>
                                </v-form>
                              </v-card-text>

                              <v-card-actions class="justify-center pt-10 pb-5">
                                <v-btn
                                  variant="outlined"
                                  color="purple"
                                  class="me-3 px-10"
                                  @click="sessionsDialog = false"
                                >
                                  {{ t("form.cancel") }}
                                </v-btn>
                                <v-btn
                                  color="purple"
                                  variant="flat"
                                  @click="updateEvent()"
                                  class="px-10"
                                  :loading="saveLoading"
                                >
                                  {{ t("form.save") }}
                                </v-btn>
                              </v-card-actions>
                            </v-card>
                          </template>
                        </v-dialog>
                      </v-list-item-title>
                    </v-list-item>

                    <v-list-item v-if="item.is_check !== 2">
                      <v-list-item-title>
                        <!-- {{ item.title }} -->

                        <v-dialog width="800">
                          <template v-slot:activator="{ props }">
                            <v-btn v-bind="props" variant="text" color="error"
                              >{{ t("form.close_course") }}
                            </v-btn>
                          </template>

                          <template v-slot:default="{ isActive }">
                            <v-card
                              class="pa-3"
                              :title="`確定要關閉「${item.name}」這堂課程嗎？`"
                            >
                              <v-card-text>
                                <!-- <p class="mb-2">
                                  確定要關閉「{{ item.name }}」這堂課程嗎？
                                </p> -->
                                <p>關閉後即可結算課程時數及點數</p>
                              </v-card-text>

                              <v-card-actions>
                                <v-spacer></v-spacer>
                                <v-btn
                                  text="確定"
                                  color="error"
                                  variant="flat"
                                  @click="closeClass(item.class_name_id)"
                                ></v-btn>

                                <v-btn
                                  :text="t('form.cancel')"
                                  variant="tonal"
                                  class="ms-3"
                                  @click="isActive.value = false"
                                ></v-btn>
                              </v-card-actions>
                            </v-card>
                          </template>
                        </v-dialog>
                      </v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>

                <v-dialog
                  v-model="studentListDialog[index]"
                  width="62.5em"
                  persistent
                >
                  <template v-slot:activator="{ props }">
                    <v-btn
                      @click="getEvent(item.class_name_id)"
                      v-bind="props"
                      color="purple"
                      variant="flat"
                      class="d-flex flex-column flex-sm-row align-start align-sm-center mt-3"
                      :disabled="item.is_check === 2"
                    >
                      <p>{{ t("form.attendance_management") }}</p>
                    </v-btn>
                  </template>

                  <v-card class="pa-5">
                    <v-card-title class="d-flex justify-end">
                      <v-btn
                        variant="text"
                        icon="mdi-close"
                        size="large"
                        @click="studentListDialog[index] = false"
                      ></v-btn>
                    </v-card-title>

                    <v-card-text class="pa-3">
                      <div
                        class="d-flex justify-center mb-10"
                        v-if="enrolledLoading"
                      >
                        <v-progress-circular
                          color="grey-lighten-4"
                          indeterminate
                        ></v-progress-circular>
                      </div>

                      <div v-else>
                        <div class="d-flex justify-center">
                          <v-tabs
                            v-model="tab"
                            color="purple"
                            align-tabs="center"
                            class="mb-5 courses-tab"
                          >
                            <v-tab :value="1" class="me-5">
                              {{ t("form.student_information") }}
                            </v-tab>
                            <v-tab :value="2">{{
                              t("form.attendance_management")
                            }}</v-tab>
                          </v-tabs>
                        </div>
                        <v-window v-model="tab">
                          <v-window-item :value="1">
                            <v-data-table
                              v-model:items-per-page="itemsPerPage"
                              :headers="approvedHeaders"
                              :items="approvedRegistration.list"
                              item-value="name"
                              class="courses-table pt-5 pb-10"
                            >
                              <template v-slot:item.real_name="{ item }">
                                <p style="width: 100px">
                                  {{ item.selectable.real_name }}
                                </p>
                              </template>
                              <template v-slot:item.payment="{ item }">
                                <div
                                  class="d-flex flex-column flex-sm-row align-start align-sm-center my-2"
                                  style="width: 100px"
                                >
                                  <v-checkbox
                                    v-model="item.selectable.payment_status"
                                    color="purple"
                                    hide-details
                                    label="已付款"
                                    @change="
                                      updateEnrolledData(item.raw, item.index)
                                    "
                                  ></v-checkbox>
                                </div>
                              </template>
                              <template v-slot:item.five_digits="{ item }">
                                <div
                                  class="d-flex flex-column flex-sm-row align-start align-sm-center my-2"
                                  style="width: 210px"
                                >
                                  <v-text-field
                                    v-model="item.selectable.five_digits"
                                    density="compact"
                                    variant="outlined"
                                    hide-details
                                    label="帳號末五碼"
                                    class="account-item"
                                    :disabled="!item.selectable.payment_status"
                                    @input="fiveDigitsInput[item.index] = true"
                                  ></v-text-field>

                                  <div style="width: 5.9375em">
                                    <div v-if="fiveDigitsInput[item.index]">
                                      <v-btn
                                        @click="
                                          updateEnrolledData(
                                            item.raw,
                                            item.index
                                          )
                                        "
                                        variant="outlined"
                                        rounded
                                        color="success"
                                        size="xs-small"
                                        class="mx-3"
                                      >
                                        <v-icon
                                          icon="mdi-check"
                                          class="pa-4"
                                        ></v-icon>
                                      </v-btn>
                                      <v-btn
                                        @click="
                                          fiveDigitsInput[item.index] = false;
                                          item.selectable.five_digits = '';
                                        "
                                        variant="outlined"
                                        rounded
                                        color="gray"
                                        size="xs-small"
                                      >
                                        <v-icon
                                          icon="mdi-close"
                                          class="pa-4"
                                        ></v-icon>
                                      </v-btn>
                                    </div>
                                    <Transition>
                                      <v-chip
                                        v-if="showChip[item.index]"
                                        class="ms-3"
                                        color="success"
                                        variant="outlined"
                                      >
                                        儲存成功
                                      </v-chip>
                                    </Transition>
                                  </div>
                                </div>
                              </template>
                            </v-data-table>
                          </v-window-item>
                          <v-window-item :value="2">
                            <div
                              class="d-flex flex-column flex-sm-row align-start align-sm-center justify-center mb-3 pt-5"
                            >
                              <v-select
                                v-model="sessionId"
                                label="選擇日期"
                                :items="session.list"
                                :item-title="
                                  (item) =>
                                    moment(item.start_time).format('YYYY/MM/DD')
                                "
                                item-value="session_id"
                                hide-details
                                density="compact"
                                variant="outlined"
                                class="mb-3"
                                style="width: 200px; flex: 0 1 auto"
                              ></v-select>

                              <!-- <v-btn color="purple">
                                結算時數</v-btn
                              > -->
                            </div>

                            <div
                              class="d-flex justify-center mb-10"
                              v-if="enrolledLoading"
                            >
                              <v-progress-circular
                                color="grey-lighten-4"
                                indeterminate
                              ></v-progress-circular>
                            </div>

                            <v-data-table
                              v-else-if="record.list.length"
                              v-model:items-per-page="itemsPerPage"
                              :headers="studentHeaders"
                              :items="record.list"
                              item-value="name"
                              class="elevation-1 courses-table pb-10"
                            >
                              <template v-slot:item.is_attend="{ item }">
                                <v-checkbox
                                  @change="saveAttendRecord(item)"
                                  v-model="item.selectable.is_attend"
                                  hide-details
                                ></v-checkbox>
                              </template>
                            </v-data-table>

                            <v-dialog
                              v-model="studentDialog"
                              width="50em"
                              persistent
                            >
                              <v-card class="pa-5">
                                <v-card-title> 學習者名單 </v-card-title>
                                <v-card-text>
                                  <v-data-table
                                    v-model:items-per-page="itemsPerPage"
                                    :headers="studentHeaders"
                                    :items="record.list"
                                    item-value="name"
                                    class="elevation-1 courses-table"
                                  >
                                    <template v-slot:item.is_attend="{ item }">
                                      <v-checkbox
                                        @change="saveAttendRecord(item)"
                                        v-model="item.selectable.is_attend"
                                        hide-details
                                      ></v-checkbox>
                                    </template>
                                  </v-data-table>
                                </v-card-text>
                                <v-card-actions class="d-flex justify-center">
                                  <v-btn
                                    color="purple"
                                    variant="text"
                                    @click="studentDialog = false"
                                  >
                                    {{ t("form.close") }}
                                  </v-btn>
                                </v-card-actions>
                              </v-card>
                            </v-dialog>
                          </v-window-item>
                        </v-window>
                      </div>
                    </v-card-text>
                  </v-card>
                </v-dialog>
              </div>
            </td>
            <td class="edit-item">
              <div class="d-flex flex-column">
                <v-btn
                  v-if="item.is_check !== 2"
                  color="blue"
                  size="small"
                  rounded="xl"
                  variant="tonal"
                  class="mt-3"
                  @click="$router.push(`/course-detail/${item.class_name_id}`)"
                >
                  <v-icon icon="mdi-open-in-new" class="pt-1 pe-2"></v-icon>
                  前往
                </v-btn>

                <v-dialog v-else width="500">
                  <template v-slot:activator="{ props }">
                    <v-btn
                      v-bind="props"
                      color="blue"
                      size="small"
                      rounded="xl"
                      variant="tonal"
                      class="mt-3"
                    >
                      重新審核
                    </v-btn>
                  </template>

                  <template v-slot:default="{ isActive }">
                    <v-card title="提示">
                      <v-card-text>
                        <p class="mb-2">確定要提交審核嗎？</p>
                        <small>（請先至 Email 確認駁回原因並完成修正）</small>
                      </v-card-text>

                      <v-card-actions class="ma-2 justify-end">
                        <v-spacer></v-spacer>

                        <v-btn
                          color="purple"
                          class="me-2"
                          variant="flat"
                          @click="resubmit(item.class_name_id)"
                          >{{ t("send") }}</v-btn
                        >

                        <v-btn
                          @click="isActive.value = false"
                          color="grey-lighten-3"
                          variant="flat"
                          >{{ t("form.cancel") }}</v-btn
                        >
                      </v-card-actions>
                    </v-card>
                  </template>
                </v-dialog>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <p v-else class="mb-3 text-h6 text-center font-weight-bold text-gray">
      {{ t("no_found") }}
    </p>

    <v-pagination
      v-if="classes.list.length"
      v-model="pageNum"
      :length="totalPages"
      rounded="circle"
      class="mt-16"
    ></v-pagination>
  </v-card>
</template>

<style lang="scss" scoped>
.user-courses {
  p,
  a {
    font-size: 0.8em;
  }
}

.courses-table {
  .v-icon::before {
    padding-top: 3px;
  }
}
</style>
