<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { useMainStore } from "@/stores/main";
import { required } from "@/utils";
import { useI18n } from "vue-i18n";
import { wsUrl } from "@/env";
import type { VideoCreate, VideoUploaded, VideoContent } from "@/interfaces";
import router from "@/router";
import Dialog from "@/components/Dialog.vue";

const { t } = useI18n();
const mainStore = useMainStore();
const WS = mainStore.videosWebSocket;
const valid = ref(true);
const title = ref("");
const zipFiles = ref();
const Form = ref();
let anchor = ref(0);
let templateId = ref(0);
let selectAnchor = ref("angela");
let selectTemplate = ref("style1");

// props
let dialog = reactive({
  msg: "",
  state: "info",
  show: false,
});

const anchorList = reactive([
  {
    anchor_id: "angela",
    name: "Angela",
  },
  {
    anchor_id: "jocelyn",
    name: "Jocelyn",
  },
  {
    anchor_id: "summer",
    name: "Summer",
  },
  {
    anchor_id: "peggy",
    name: "Peggy",
  },
]);

const templateList = reactive([
  {
    template_id: "style1",
    img: "鏡面-01",
  },
  {
    template_id: "style2",
    img: "鏡面-02",
  },
  {
    template_id: "style3",
    img: "鏡面-03",
  },
  {
    template_id: "style4",
    img: "鏡面-04",
  },
]);

let anchorLang = ref("中文");
let items = reactive([
  { lang: "中文", id: 0 },
  { lang: "英文", id: 1 },
]);

// 取得圖片路徑
const getImageUrl = (imgFolder: string, name: string) => {
  return new URL(`../../assets/img/${imgFolder}/${name}.png`, import.meta.url)
    .href;
};

watch(dialog, (newVal) => {
  if (!newVal.show && newVal.state === "error") {
    return;
  } else if (!newVal.show && newVal.state === "success") {
    router.push("/main/progress");
  }
});

watch(anchor, (newVal) => {
  selectAnchor.value = anchorList[newVal].anchor_id;
});

watch(templateId, (newVal) => {
  selectTemplate.value = templateList[newVal].template_id;
});

// 片段
let fragments = reactive({
  list: [] as any[],
});

let videoContent: VideoContent = reactive({
  title: "",
  text: "",
  caption: [],
});

// 新增片段
function addFragments() {
  fragments.list.push(JSON.parse(JSON.stringify(videoContent)));
}

// 刪除片段
function deleteFragments(index: number) {
  deleteDialog[index] = false;
  fragments.list.splice(index, 1);
}

addFragments();

// 新增腳本
function addCaption(index: number) {
  let text: string = fragments.list[index].text;
  fragments.list[index].caption.push(text);
  fragments.list[index].text = ""; // 清空腳本
}

// 圖片
let imgs = reactive({
  list: [] as File[],
});

function addImgsFile(item: any) {
  const selectedFiles = item.target.files;

  for (let i = 0; i < selectedFiles.length; i++) {
    imgs.list.push(selectedFiles[i]);
  }
}

async function Submit() {
  let files: any = imgs.list;
  let data = JSON.parse(JSON.stringify(fragments.list));

  for (let i = 0; i < data.length; i++) {
    data[i].text = data[i].caption; // 將 caption 的值設置給 text
    delete data[i].caption; // 刪除 caption 屬性
    console.log("('>>> data", data);
  }

  console.log("data", data);
  console.log("files", files);

  const response = await mainStore.uploadVideoContent(data, files);

  console.log("response", response);

  // WS.send("subscribe");
  // await (Form as any).value.validate();
  // if (valid.value) {
  //   valid.value = false;

  //   const video_data: VideoCreate = {
  //     title: title.value,
  //     anchor: selectAnchor.value,
  //     style: selectTemplate.value,
  //     lang: "zh",
  //   };

  //   const ret: VideoUploaded = await mainStore.uploadPlot(
  //     video_data,
  //     zipFiles.value[0]
  //   );

  //   if (ret.accepted) {
  //     dialog.msg = t("acceptZipMessage");
  //     dialog.state = "success";
  //     dialog.show = true;
  //   } else {
  //     dialog.msg = ret.error_message!;
  //     dialog.state = "error";
  //     dialog.show = true;
  //   }

  //   valid.value = true;

  //   // (Form as any).value.reset();
  // }
}

let deleteDialog = reactive([] as any);
</script>

<template>
  <v-container fluid>
    <v-card class="ma-3 pa-5">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">{{ t("makeVideo") }}</h3>
      </v-card-title>
      <v-card-text>
        <v-expansion-panels class="anchor-list">
          <v-expansion-panel title="選擇主播">
            <v-expansion-panel-text class="p-0">
              <v-item-group mandatory v-model="anchor">
                <v-container fluid>
                  <ul>
                    <li v-for="n in anchorList" :key="n.anchor_id">
                      <v-item v-slot="{ isSelected, toggle }">
                        <v-card
                          :color="isSelected ? 'primary' : ''"
                          class="d-flex flex-column align-center"
                          dark
                          @click="toggle"
                          :title="n.name"
                        >
                          <v-scroll-y-transition>
                            <img
                              :src="getImageUrl('anchor', n.anchor_id)"
                              alt=""
                            />
                          </v-scroll-y-transition>
                        </v-card>
                      </v-item>
                    </li>
                  </ul>
                </v-container>
              </v-item-group>
            </v-expansion-panel-text>
          </v-expansion-panel>
        </v-expansion-panels>

        <v-expansion-panels class="template-list mt-6">
          <v-expansion-panel title="選擇模板">
            <v-expansion-panel-text class="p-0">
              <v-sheet class="mx-auto">
                <v-slide-group
                  v-model="templateId"
                  selected-class="bg-primary"
                  show-arrows
                >
                  <v-slide-group-item
                    v-for="n in templateList"
                    :key="n.template_id"
                    v-slot="{ isSelected, toggle, selectedClass }"
                  >
                    <v-card
                      color="grey-lighten-1"
                      :class="['ma-4', selectedClass]"
                      @click="toggle"
                    >
                      <span
                        class="choose-btn"
                        :class="{ 'active-color': isSelected }"
                      >
                        <v-icon icon="done" color="white" />
                      </span>
                      <img :src="getImageUrl('template', n.img)" alt="" />
                    </v-card>
                  </v-slide-group-item>
                </v-slide-group>
              </v-sheet>
            </v-expansion-panel-text>
          </v-expansion-panel>
        </v-expansion-panels>
      </v-card-text>
      <!-- <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="Submit" :disabled="!valid" variant="outlined">
          {{ t("send") }}
        </v-btn>
      </v-card-actions> -->
    </v-card>

    <v-card class="mt-10 ma-3 pa-sm-5">
      <v-card-title primary-title>
        <h3 class="card-title mb-3">{{ t("makeVideo") }}</h3>
      </v-card-title>
      <v-card-text class="mx-auto" style="max-width: 500px">
        <v-form v-model="valid" ref="Form" class="upload-form">
          <div
            class="list-item"
            v-for="(item, index) in fragments.list"
            :key="index"
          >
            <div class="d-flex justify-end">
              <v-btn
                icon="close"
                size="small"
                variant="text"
                color="grey-lighten-1"
                :disabled="index === 0"
              >
                <v-icon icon="close" color="grey-lighten-1" />

                <v-dialog
                  v-model="deleteDialog[index]"
                  activator="parent"
                  width="350"
                >
                  <v-card>
                    <v-card-text> 確定要刪除此片段？ </v-card-text>
                    <v-card-actions class="d-flex justify-center">
                      <v-btn color="gray" @click="deleteDialog[index] = false"
                        >取消</v-btn
                      >
                      <v-btn color="red" @click="deleteFragments(index)"
                        >刪除</v-btn
                      >
                    </v-card-actions>
                  </v-card>
                </v-dialog>
              </v-btn>
            </div>

            <h4 class="mb-5">片段 {{ index + 1 }}</h4>

            <div class="img-item">
              <div class="img-inputs">
                <input @change="addImgsFile($event)" type="file" class="file" />
                <p>
                  點擊上傳圖片或影片 <br />
                  或將檔案拖曳至此區塊
                </p>
              </div>
            </div>

            <v-text-field
              label="標題"
              v-model="item.title"
              :rules="required()"
              prepend-icon="title"
              hint="不超過中文 10 字／英文 20 字"
            >
            </v-text-field>

            <div class="d-flex">
              <v-text-field
                label="請輸入腳本"
                v-model="item.text"
                prepend-icon="message"
                hint="不超過中文 20 字／英文 40 字"
              >
              </v-text-field>

              <v-btn
                @click="addCaption(index)"
                icon="check"
                size="small"
                color="success"
                variant="text"
                class="ma-2"
              ></v-btn>

              <!-- <v-btn
                icon="close"
                size="small"
                variant="text"
                class="mt-2"
                color="red"
              ></v-btn> -->
            </div>

            <ul class="caption-list">
              <li v-for="(e, i) in fragments.list[index].caption" :key="index">
                <div class="d-flex align-center mb-5">
                  <p class="me-5">{{ i + 1 }}.</p>
                  <v-text-field
                    variant="outlined"
                    v-model="fragments.list[index].caption[i]"
                    hide-details
                  ></v-text-field>

                  <!-- {{ `${index+1}. ${ item }` }} -->
                  <v-btn
                    icon="close"
                    size="small"
                    variant="text"
                    class="mx-2"
                    color="red"
                  ></v-btn>
                </div>
              </li>
            </ul>
          </div>
        </v-form>

        <div class="d-flex">
          <v-btn
            @click="addFragments()"
            icon="add"
            size="large"
            color="primary"
            class="mx-auto"
          ></v-btn>
        </div>
      </v-card-text>
      <!-- <v-card-actions>
        <v-spacer></v-spacer>
        <v-btn @click="Submit" :disabled="!valid" variant="outlined">
          {{ t("send") }}
        </v-btn>
      </v-card-actions> -->
    </v-card>

    <div class="d-flex justify-end pa-5">
      <v-btn @click="Submit" variant="flat" color="primary">
        {{ t("send") }}
      </v-btn>
    </div>

    <template>
      <div class="text-center">
        <Dialog
          :msg="dialog.msg"
          :state="dialog.state"
          :dialog="dialog.show"
          @close="dialog.show = false"
        ></Dialog>
      </div>
    </template>
  </v-container>
</template>

<style lang="scss">
.upload-form {
  h4 {
    font-size: 20px;
  }

  .list-item {
    padding: 15px 25px 25px;
    margin-bottom: 30px;
    border-radius: 20px;
    border: 1px solid #b5b5b5;
    // box-shadow: 2px 2px 5px #ccc;
  }

  .img-item {
    label {
      border: 1px solid #000;
      border-radius: 10px;
    }
  }

  .img-inputs {
    margin-bottom: 25px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
    border: 1px dashed #9f9f9f;
    background-color: #f6f6f6;
    p {
      position: absolute;
      font-size: 16px;
      color: #818181;
      text-align: center;
      line-height: 26px;
    }
    .file {
      width: 100%;
      padding: 50px;
      position: relative;
      opacity: 0;
      z-index: 10;
      cursor: pointer;
    }
  }

  .v-input--horizontal .v-input__prepend {
    margin-inline-end: 10px;
  }
}

.anchor-list {
  ul {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, max-content));
    grid-gap: 20px;
    justify-content: center;
    padding: initial;
    li {
      list-style-type: none;
    }
  }
  img {
    width: 100%;
    height: 140px;
    object-fit: cover;
  }

  .v-card--variant-elevated {
    box-shadow: 0px 2px 5px 1px
        var(--v-shadow-key-umbra-opacity, rgba(0, 0, 0, 0.2)),
      0px 1px 1px 0px var(--v-shadow-key-penumbra-opacity, rgba(0, 0, 0, 0.14)),
      0px 1px 3px 0px var(--v-shadow-key-penumbra-opacity, rgba(0, 0, 0, 0.12));
  }

  .v-card-item {
    padding: 0;
    text-align: center;
    .v-card-title {
      font-size: 18px;
    }
  }
  .bg-success {
    background: linear-gradient(
      -225deg,
      rgb(234, 84, 19) 35%,
      rgb(178, 69, 146) 100%
    ) !important;
  }
  .v-expansion-panel-text__wrapper {
    padding: 0 !important;
  }
}

.anchor-list,
.template-list {
  padding-left: 40px;
  .v-expansion-panel-title {
    height: 55px;
    min-height: 0;
  }
}

.template-list {
  img {
    width: 100%;
    height: 180px;
  }
  .choose-btn {
    padding: 5px;
    position: absolute;
    right: 8px;
    bottom: 13px;
    background: #ccc;
    border-radius: 100px;
  }
  .active-color {
    background: #ea5413;
  }
}

.caption-list {
  li {
    font-size: 16px;
    list-style: none;
  }
}
</style>
