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

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

let user = reactive({
  name: "",
  user_name: "",
  birthday: "",
  gender: "",
  phone: "",
  address: "",
  position: [], // 身份
  identity: [], // 類別
});

let positionList = ref([]);
let identityList = ref([]);
let email = ref("");
let phoneCode = ref("+886");
let phone = ref("");
let city = ref("臺北市");
let address = ref("");
let isLoading = ref(false);
// let alertState = ref(false);
let isExist = ref(false); // 資料是否已存在

let token = store.token;

// 更新使用者資料
async function saveUserInfo() {
  isLoading.value = true;

  user.phone = `${phoneCode.value} ${phone.value}`;
  user.address = city.value + address.value;
  user.birthday = store.formatDate(user.birthday);
  // 陣列轉字串
  user.position = `[${positionList.value.join(",")}]`;
  user.identity = `[${identityList.value.join(",")}]`;

  console.log("user", user);

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

  if (isExist.value) {
    updateUserInfo(formData);
  } else {
    addUserInfo(formData);
  }
}

// 新增資料
async function addUserInfo(formData) {
  try {
    const response = await axios.post(
      `${store.apiUrl}/api/input_information?access_token=${token}`,
      formData
    );
    console.log("新增 response", response);
    if (response.status === 200) {
      setUserInfo;
    }
    isLoading.value = false;
    alert("儲存成功！");
  } catch (error) {
    console.error(error);
  }
}

// 更新資料
async function updateUserInfo(formData) {
  try {
    console.log("try");
    const response = await axios.post(
      `${store.apiUrl}/api/update_information?access_token=${token}`,
      formData
    );
    console.log("更新 response", response);

    setTimeout(() => {
      isLoading.value = false;
      alert("儲存成功！");
    }, 1000);
  } catch (error) {
    console.error(error);
  }
}

let isCrafts = ref(false); // 身份是否為工藝教育者
let getUserLoading = ref(false);

onMounted(async () => {
  getUserLoading.value = true;
  await store.getUserInfo();
  await setUserInfo();
  // setTimeout(() => {
  //   getUserInfo();
  // }, 500);
});

// 取得使用者資料
async function setUserInfo() {
  if (Object.keys(store.userInfo).length) {
    let userInform = store.userInfo;

    console.log("Profile 取得使用者資料", userInform);

    email.value = userInform.email;
    user.user_name = userInform.user_name;

    if (userInform.position) {
      let position = userInform.position;
      console.log("user.position", position);

      // 判斷身份
      if (position["學習者"]) {
        positionList.value.push("1");
      }
      if (position["開課工藝家"]) {
        isCrafts.value = true;
        positionList.value.push("2");
      }
    }

    if (userInform.identify) {
      let identifyStr = userInform.identify.substring(
        1,
        userInform.identify.length - 1
      ); // 移除 [] 後將字串轉為陣列
      identityList.value = identifyStr.split(",");
    }

    if (!userInform.exist) {
      isExist.value = false;
    } else {
      isExist.value = true;

      // 遍歷物件屬性
      Object.keys(userInform).forEach((key) => {
        if (user[key] !== undefined) {
          user[key] = userInform[key];
        }
      });

      if (userInform.phone) {
        // 手機
        const phoneSplit = userInform.phone.split(" ");

        if (phoneSplit.length === 2) {
          phoneCode.value = phoneSplit[0];
          phone.value = phoneSplit[1];
        } else {
          phone.value = phoneSplit[1];
        }
      }

      if (userInform.address) {
        // 地址
        city.value = userInform.address.substring(0, 3);
        address.value = userInform.address.substring(3);
      }
    }
    getUserLoading.value = false;
  } else {
    store.loginState = false;
    console.log("setUserInfo error");
    localStorage.removeItem("token");
    // console.error(error);
  }
}

let tab = ref(null);
const genderGroup = reactive(["男", "女", "多元"]);
const displayText = (item) => `${item.country} ${item.code}`;
const requiredRule = (value) => !!value || "此欄位為必填";

// 履歷
let resume = reactive({
  teacher_name: "", // 工藝教育者姓名
  work_type: "", // 工作性質
  experience: "", // 教學經驗
  expertise: "", // 專長工藝技能
  license: "", // 工藝相關證照
  media: "", // 社群媒體
  files: [], // 作品集
  introduction: "", // 老師介紹
});

// 取得工藝教育者履歷
(async () => {
  let token = localStorage.getItem("token");
  try {
    const response = await axios.get(
      `${store.apiUrl}/api/get_user_resume?access_token=${token}`
    );

    if (response.data.user_resume) {
      // 遍歷物件屬性
      Object.keys(response.data.user_resume).forEach((key) => {
        if (resume[key] !== undefined) {
          resume[key] = response.data.user_resume[key];
        }
      });
    }

    console.log("resume", resume);
  } catch (error) {
    console.error(error);
  }
})();

// 更新工藝教育者履歷
async function saveResume() {
  console.log("saveResume");
}

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

// const fileInputClick = () => {
//   portfolioImgRef.value.click();
// };

// 作品集圖片
let portfolioImg = ref([]);
let portfolioImgList = ref([]);

const handlePortfolioImg = (files) => {
  for (let index = 0; index < files.length; index++) {
    const file = files[index];
    let url = URL.createObjectURL(file);
    portfolioImgList.value.push(url);
  }
};

watch(portfolioImg, (newFiles) => {
  if (newFiles.length > 0) {
    handlePortfolioImg(newFiles);
  }
});

// 編輯藝文中心會員資料
async function editMocProfile() {
  window.location.href = `https://member.moc.gov.tw/MOCMC/M0004/list?SYS_ID=CRAFT_NTCRI`;
}

// 身份類別
let typeList = [
  "系統管理者",
  "職能治療師",
  "設計師",
  "藝術家",
  "跨域工藝師",
  "協槓青年",
  "傳統工藝守護者",
  "加工製造者",
  "修復師",
  "評論家",
  "策展人",
  "鑑賞師",
  "收藏家",
];

// 材質
let materialList = ["瓷土", "陶土", "循環材料"];
// 技能
let technicalTypeList = ["陶藝", "手擠坯", "手拉坏"];
// 技法
let technicalList = ["時尚", "家飾", "屏風", "雕塑", "陶板成形"];
// 機具
let productList = ["機具", "織布"];
</script>

<template>
  <div v-if="getUserLoading" class="d-flex justify-center py-16">
    <v-progress-circular
      color="grey-lighten-4"
      indeterminate
    ></v-progress-circular>
  </div>

  <v-card v-else class="h-100 px-10 profile-card">
    <v-tabs v-model="tab" color="purple" align-tabs="center" class="mb-16">
      <v-tab :value="1">{{ t("profile.about_me") }}</v-tab>
      <v-tab :value="2">{{ t("profile.creator") }}</v-tab>
      <v-tab :value="3">{{ t("profile.processing_manufacturers") }}</v-tab>
      <!-- <v-tab v-if="isCrafts" :value="2">工藝教育者履歷</v-tab> -->
    </v-tabs>
    <v-window v-model="tab">
      <v-window-item :value="1">
        <v-form @submit.prevent>
          <p class="mb-5">{{ t("profile.identity") }}</p>
          <div class="d-flex">
            <v-chip color="purple"> 學習者 </v-chip>
            <v-chip v-if="isCrafts" color="purple" class="ms-2">
              開課工藝教育者
            </v-chip>
          </div>

          <v-label class="mt-10">
            <p class="d-flex mb-5">
              {{ t("category") }}
            </p>

            <v-select
              v-model="identityList"
              :items="typeList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="mt-10">
            <p class="d-flex mb-5">
              {{ t("profile.displayName") }}<span class="mark">*</span>
            </p>
            <v-text-field
              v-model="user.user_name"
              :rules="[(v) => !!v || '請輸入您的名稱']"
              variant="outlined"
              density="comfortable"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label class="mt-3">
            <p class="d-flex my-3">{{ t("profile.gender") }}</p>
            <v-chip-group
              v-model="user.gender"
              selected-class="text-purple"
              mandatory
            >
              <v-chip
                v-for="item in genderGroup"
                :key="item"
                :value="item"
                filter
              >
                {{ item }}
              </v-chip>
            </v-chip-group>
          </v-label>

          <v-btn
            :loading="isLoading"
            variant="flat"
            color="purple"
            class="px-8 mt-16"
            @click="saveUserInfo()"
          >
            {{ t("profile.save") }}
          </v-btn>

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

          <p class="d-flex my-3">{{ t("profile.account") }}／Email</p>
          <p class="text-gray">{{ email }}</p>

          <v-label>
            <p class="d-flex my-3">{{ t("profile.account") }}</p>
            <p class="text-gray">{{ store.mocProfile.NAME }}</p>
          </v-label>

          <v-label>
            <p class="d-flex my-3">{{ t("profile.birthday") }}</p>
            <p class="text-gray">
              {{ store.mocProfile.BIRTH_DATE_YEAR }}
              {{ store.mocProfile.BIRTH_DATE_MONTH }}
              {{ store.mocProfile.BIRTH_DATE_DAY }}
            </p>
          </v-label>

          <v-label>
            <p class="d-flex my-3">
              {{ t("profile.phoneNumber") }}<span class="mark">*</span>
            </p>
            <p class="text-gray">{{ store.mocProfile.MOBILEPHONE }}</p>
          </v-label>

          <v-label>
            <p class="d-flex my-3">{{ t("profile.address") }}</p>
            <p class="text-gray">{{ store.mocProfile.ZIP_NAME }}</p>
          </v-label>

          <v-btn
            :loading="isLoading"
            variant="flat"
            color="purple"
            class="px-8 mt-16 mb-10"
            @click="editMocProfile()"
          >
            {{ t("profile.edit_profile") }}
          </v-btn>
        </v-form>
      </v-window-item>

      <!-- 創作者 -->
      <v-window-item :value="2">
        <v-form @submit.prevent>
          <v-label class="mt-5">
            <p class="d-flex mb-5">
              {{ t("profile.creator_name") }}<span class="mark">*</span>
            </p>
            <v-text-field
              :rules="[(v) => !!v || '請輸入您的姓名']"
              variant="outlined"
              density="compact"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">{{ t("profile.job_position") }}</p>
            <v-text-field
              variant="outlined"
              density="compact"
              class="d-block"
              disabled
              >工藝家</v-text-field
            >
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">{{ t("profile.company") }}</p>
            <v-text-field
              variant="outlined"
              density="compact"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label>
            <p class="d-flex mb-5">{{ t("profile.about_me") }}</p>
            <v-textarea rows="5" variant="outlined"></v-textarea>
          </v-label>

          <v-divider class="mt-10 mb-13"></v-divider>

          <p class="text-h5 font-weight-bold">{{ t("skill") }}</p>

          <v-label class="mt-5">
            <p class="d-flex mb-5">{{ t("material_tags") }}</p>

            <v-select
              :items="materialList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="mt-10">
            <p class="d-flex mb-5">{{ t("skill_tags") }}</p>

            <v-select
              :items="technicalTypeList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-divider class="mt-15 mb-13"></v-divider>

          <p class="text-h5 font-weight-bold">{{ t("partners") }}</p>

          <ul class="mb-16">
            <li class="my-5">
              <v-btn color="purple" variant="outlined">
                <v-icon icon="mdi-plus" class="pt-1 pe-3"> </v-icon>
                <p>{{ t("create_partners") }}</p>
              </v-btn>
            </li>
            <li class="d-flex justify-space-between">
              <div>
                <p>李建佑</p>
                <p class="mt-2">其他加工製造商</p>
              </div>
              <span>
                <v-chip color="green"> 已通過 </v-chip>
              </span>
            </li>
          </ul>

          <div class="d-flex justify-center mt-5 mb-10">
            <v-btn
              :loading="isLoading"
              variant="flat"
              color="purple"
              class="px-8"
              @click="saveResume()"
            >
              {{ t("form.save") }}
            </v-btn>
          </div>
        </v-form>
      </v-window-item>

      <!-- 加工製造者 -->
      <v-window-item :value="3">
        <v-form @submit.prevent>
          <p class="text-h5 font-weight-bold">
            {{ t("profile.processing_techniques_info") }}
          </p>

          <v-label class="mt-10">
            <p class="d-flex mb-5">
              {{ t("profile.technique_name") }}<span class="mark">*</span>
            </p>
            <v-text-field
              :rules="[requiredRule]"
              variant="outlined"
              density="compact"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">
              {{ t("description") }}<span class="mark">*</span>
            </p>
            <v-textarea rows="5" variant="outlined"></v-textarea>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">{{ t("profile.technique_type") }}</p>

            <v-select
              :items="technicalTypeList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">
              {{ t("profile.applied_products") }}<span class="mark">*</span>
            </p>
            <v-select
              :items="productList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.applied_materials") }}<span class="mark">*</span>
            </p>

            <v-select
              :items="materialList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.manufactured_tools") }}<span class="mark">*</span>
            </p>
            <v-select
              :items="productList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.technique_tags") }}
            </p>

            <v-select
              :items="technicalList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-divider class="mt-10 mb-13"></v-divider>

          <p class="text-h5 font-weight-bold">
            {{ t("profile.collaboration_case_info") }}
          </p>

          <v-label class="mt-10">
            <p class="d-flex mb-5">
              {{ t("profile.case_name") }}<span class="mark">*</span>
            </p>
            <v-text-field
              :rules="[requiredRule]"
              variant="outlined"
              density="compact"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">
              {{ t("description") }}<span class="mark">*</span>
            </p>
            <v-textarea rows="5" variant="outlined"></v-textarea>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.products_materials") }}<span class="mark">*</span>
            </p>

            <v-select
              :items="materialList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.applied_technique") }}<span class="mark">*</span>
            </p>

            <v-select
              :items="technicalList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <v-label class="mt-5">
            <p class="d-flex mb-5">
              {{ t("profile.production_quantity") }}<span class="mark">*</span>
            </p>
            <v-text-field
              :rules="[requiredRule]"
              variant="outlined"
              density="compact"
              class="d-block"
              type="number"
            ></v-text-field>
          </v-label>

          <v-label class="my-5">
            <p class="d-flex mb-5">
              {{ t("profile.collaboration_tags") }}<span class="mark">*</span>
            </p>

            <v-select
              :items="technicalList"
              multiple
              hide-details
              variant="outlined"
              density="compact"
            >
              <template #selection="{ item }">
                <v-chip color="purple" class="me-1">{{ item.title }}</v-chip>
              </template>
            </v-select>
          </v-label>

          <div class="d-flex justify-center mt-5 mb-10">
            <v-btn
              :loading="isLoading"
              variant="flat"
              color="purple"
              class="px-8"
              @click="saveResume()"
            >
              {{ t("form.save") }}
            </v-btn>
          </div>
        </v-form>
      </v-window-item>

      <!-- 工藝教育者履歷 -->
      <!-- <v-window-item :value="2">
        <v-form @submit.prevent>
          <v-label class="mt-5">
            <p class="d-flex mb-5">工藝教育者姓名<span class="mark">*</span></p>
            <v-text-field
              v-model="resume.teacher_name"
              :rules="[(v) => !!v || '請輸入您的姓名']"
              class="d-block"
            ></v-text-field>
          </v-label>

          <v-label>
            <p class="pb-5 pe-3">工作性質<span class="mark">*</span></p>
            <v-radio-group v-model="resume.work_type" inline color="purple">
              <v-radio label="全職" value="全職"></v-radio>
              <v-radio label="兼職" value="兼職" class="ps-3"></v-radio>
            </v-radio-group>
          </v-label>

          <v-label>
            <p class="pb-5 pe-3">教學經驗</p>
            <v-radio-group v-model="resume.experience" inline color="purple">
              <v-radio label="0-5 年" value="0-5 年"></v-radio>
              <v-radio label="5-10 年" value="5-10 年" class="ps-3"></v-radio>
              <v-radio label="10-20 年" value="10-20 年" class="ps-3"></v-radio>
              <v-radio
                label="20 年以上"
                value="20 年以上"
                class="ps-3"
              ></v-radio>
            </v-radio-group>
          </v-label>

          <v-label>
            <p class="pb-5 pe-3">專長工藝技能<span class="mark">*</span></p>
            <v-text-field
              v-model="resume.expertise"
              :rules="[requiredRule]"
            ></v-text-field>
          </v-label>

          <v-label>
            <p class="d-flex">社群媒體</p>
            <span class="d-block py-3 hint"
              >工藝老師經營之網站或社群媒體，可貼網址</span
            >
            <v-text-field v-model="resume.media"></v-text-field>
          </v-label>

          <v-label class="d-block">
            <p class="d-flex">講師作品集</p>

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

          <v-btn @click="fileInputClick()" color="purple" class="my-5"
            >選擇相片上傳</v-btn
          >

          <v-row class="img-list">
            <v-col cols="4" v-for="(item, index) in 6" :key="index">
              <div v-if="!portfolioImgList.length" class="item"></div>
              <div
                v-else
                class="item"
                :style="{
                  backgroundImage: `url('${portfolioImgList[index]}')`,
                }"
              ></div>
            </v-col>
          </v-row>

          <v-label>
            <p class="d-flex mb-5">工藝教育者自我介紹</p>
            <v-textarea v-model="resume.introduction" rows="5"></v-textarea>
          </v-label>

          <div class="d-flex justify-center mt-5 mb-10">
            <Transition>
              <v-alert
                v-if="alertState"
                type="success"
                variant="outlined"
                density="compact"
              >
                儲存成功
              </v-alert>
            </Transition>

            <v-btn
              :loading="isLoading"
              variant="flat"
              color="purple"
              class="px-8"
              @click="saveResume()"
            >
              儲存
            </v-btn>
          </div>
        </v-form>
      </v-window-item> -->
    </v-window>

    <!-- <div class="title">
      <h4>關於我</h4>
    </div> -->
  </v-card>
</template>

<style lang="scss">
.profile-card {
  p {
    letter-spacing: 0.0625em;
  }

  .img-list {
    .item {
      height: 10.625em;
      border-radius: 0.3125em;
      background-color: #ccc; // 預設灰底
      background-repeat: no-repeat;
      background-position: center;
      background-size: cover;
    }
  }

  .v-btn {
    font-size: 1em !important;
  }

  .v-label {
    margin-top: 1.875em;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
  }

  .v-checkbox,
  .v-radio-group {
    .v-label {
      margin-top: 0;
    }
  }

  // .v-chip__content {
  //   padding: 0 0.5em;
  // }

  .v-alert {
    position: absolute;
    padding: 0.1875em 0.625em;
    right: 13.9375em;
    transition: all 0.3s;
  }

  .v-tabs {
    margin: 1.25em 0;

    .v-tab__slider {
      height: 0.1875em;
    }

    // .v-slide-group__container {
    //   overflow: unset;
    // }

    .v-btn__content {
      font-size: 1.375em;
    }
  }

  .v-tabs--density-default {
    --v-tabs-height: 4.0625em;
  }
}
</style>
