<script setup>
import Footer from "@/components/Footer.vue";
import FlexView from "@/components/FlexView.vue";

import { ref, watch, computed,  nextTick } from "vue";

import { useCardStore } from '@/store/card'

import { useRouter } from "vue-router";

import axios from "axios";
import _ from "lodash";

import { showToast, showLoadingToast, showSuccessToast, showFailToast } from "vant";

import { onMounted } from "vue";

const URL = window.URL || window.webkitURL;

const cardStore = useCardStore();

const router = useRouter();

const showNfc = ref(false);
const showPreview = ref(false);
const showMovie = ref(false);

const showTitleSizePicker = ref(false);
const showDescSizePicker = ref(false);

let flexRef = ref(null);

const showMvPopup = () => {
  showMovie.value = true;
};


// let state = reactive({
//   imagePath: "",
//   previewImage: null,
//   fileList: [],
//   showFooter: true,
// });

const form = ref({
  page: 1,
  title: "商務卡片",
  showNfc: true,
  json5: {
    altText: "",
    btnHeight: "md",
    descSize: "sm",
    titleSize: "xl",
    cards: [
      {
        bgColor: "#ffffff",
        desc: "",
        descColor: "#000000",
        image: "",
        link: "",
        title: "",
        titleSize: "xl",
        descSize: "sm",
        titleColor: "#000000",
        ratio: "20:13",
      },
    ],
  },
});

const defaultTheme = {
  bgColor: "#ffffff",
  desc: "",
  descColor: "#000000",
  image: "",
  // link: "",
  title: "",
  titleSize: "xl",
  descSize: "sm",
  titleColor: "#000000",
  ratio: "4:3",
  isShow: true
}


onMounted(() => {
  if (cardStore.cusCard.cus_card && cardStore.cusCard.cus_card.length > 0) {
    form.value = JSON.parse(cardStore.cusCard.cus_card);
  }
});

const sizeColumns = ref([
  { text: "xxs", value: "xxs" },
  { text: "xs", value: "xs" },
  { text: "sm", value: "sm" },
  { text: "md", value: "md" },
  { text: "lg", value: "lg" },
  { text: "xl", value: "xl" },
  { text: "xxl", value: "xxl" },
  { text: "3xl", value: "3xl" },
  { text: "4xl", value: "4xl" },
  { text: "5xl", value: "5xl" },
]);

watch(() => form.value.title,
  (newVal) => {
    form.value.json5.altText = newVal;
  }
);

const addCard = () => {
  form.value.json5.cards.push({
    bgColor: "#ffffff",
    desc: "",
    descColor: "#000000",
    image: "",
    // link: "",
    title: "",
    titleSize: "xl",
    descSize: "sm",
    titleColor: "#000000",
    ratio: "20:13",
  });
  form.value.page = form.value.json5.cards.length;
};

const delCard = (page) => {
  if (page > 1) {
    form.value.page = page - 1;
  }
  form.value.json5.cards.splice(page - 1, 1);
};

const addBtn = (page) => {
  if (!form.value.json5.cards[page - 1].btns) {
    form.value.json5.cards[page - 1].btns = [];
  }

  form.value.json5.cards[page - 1].btns.push({
    color: "#42659a",
    link: "",
    style: "primary",
    text: "",
    btnHeight: "md",
  });

  nextTick(() => {
    window.scrollTo(0, document.body.scrollHeight);
  });
};

const addShareBtn = (page) => {
  if (!form.value.json5.cards[page - 1].btns) {
    form.value.json5.cards[page - 1].btns = [];
  }

  form.value.json5.cards[page - 1].btns.push({
    color: "#42659a",
    link: `${import.meta.env.VITE_APP_SEND_URL}?userid=${sessionStorage.getItem(
      "uid"
    )}&cardid=2`,
    style: "primary",
    text: "分享好友",
    btnHeight: "md",
  });
};

const moveCard = (type, page) => {
  if (type === 0) {
    if (page !== 1) {
      [form.value.json5.cards[page - 1], form.value.json5.cards[page - 2]] = [
        form.value.json5.cards[page - 2],
        form.value.json5.cards[page - 1],
      ];
      form.value.page = page - 1;
    }
  } else {
    if (page !== form.value.json5.cards.length) {
      [form.value.json5.cards[page], form.value.json5.cards[page - 1]] = [
        form.value.json5.cards[page - 1],
        form.value.json5.cards[page],
      ];
      form.value.page = page + 1;
    }
  }
};

const delBtn = (index) => {
  form.value.json5.cards[form.value.page - 1].btns.splice(index, 1);
  if (form.value.json5.cards[form.value.page - 1].btns.length === 0) {
    delete form.value.json5.cards[form.value.page - 1].btns;
  }
  showSuccessToast("刪除成功");
};

const moveBtn = (type, index) => {
  if (type === 0) {
    if (index !== 0) {
      [
        form.value.json5.cards[form.value.page - 1].btns[index],
        form.value.json5.cards[form.value.page - 1].btns[index - 1],
      ] = [
          form.value.json5.cards[form.value.page - 1].btns[index - 1],
          form.value.json5.cards[form.value.page - 1].btns[index],
        ];
    }
  } else {
    if (index + 1 !== form.value.json5.cards[form.value.page - 1].btns.length) {
      [
        form.value.json5.cards[form.value.page - 1].btns[index + 1],
        form.value.json5.cards[form.value.page - 1].btns[index],
      ] = [
          form.value.json5.cards[form.value.page - 1].btns[index],
          form.value.json5.cards[form.value.page - 1].btns[index + 1],
        ];
    }
  }
};

const afterRead = async (file, name) => {
  crop.value.show = true
  const ofile = file.file
  crop.value.img = URL.createObjectURL(ofile);

  // const imgFile = new FormData();
  // imgFile.append("fileType", "IMAGE");
  // imgFile.append("file", file.file);

  // showLoadingToast({
  //   duration: 0,
  //   message: "圖片上傳中...",
  //   forbidClick: true,
  // });

  // let res = await axios.post(
  //   `${import.meta.env.VITE_APP_API_URL}/card/uploadfile`,
  //   imgFile,
  //   {}
  // );

  // if (res.data.code == 200) {
  //   form.value.json5.cards[form.value.page - 1].image = res.data.data;

  //   showSuccessToast("上傳成功");
  // } else {
  //   showToast.fail("上傳失敗");
  // }

  // return;
};

// START: 圖片剪裁
// Author: Wayne
import { Cropper } from "vue-advanced-cropper";
import "vue-advanced-cropper/dist/style.css";

const myCrop = ref(null);

const crop = ref({
  show: false,
  img: null,
  outputType: "jpeg",
  autoCrop: true,
  autoCropWidth: 200,
  autoCropHeight: 200,
});

const onCrop = () => {
  const { canvas } = myCrop.value.getResult();
  if (canvas) {
    const imgFile = new FormData();
    canvas.toBlob(async (blob) => {
      let ufile = new File([blob], "image.jpg");
      imgFile.append("fileType", "IMAGE");
      imgFile.append("file", ufile);

      crop.value.show = false;

      showLoadingToast({
        duration: 0,
        message: "圖片上傳中...",
        forbidClick: true,
      });

      let res = await axios.post(
        `${import.meta.env.VITE_APP_API_URL}/card/uploadfile`,
        imgFile,
        {}
      );

      if (res.data.code == 200) {
        form.value.json5.cards[form.value.page - 1].image = res.data.data;

        showSuccessToast("上傳成功");
      } else {
        showFailToast("上傳失敗");
      }
    }, "image/jpeg");
  }

  return;
};

const onClose = () => {
  crop.value.show = false;
};

const setRatio = (type) => {
  switch (type) {
    case 1:
      form.value.json5.cards[form.value.page - 1].ratio = '4:3';
      defaultTheme.ratio = '4:3'
      break;
    case 2:
      form.value.json5.cards[form.value.page - 1].ratio = '1:1';
      defaultTheme.ratio = '1:1'
      break;
    case 3:
      form.value.json5.cards[form.value.page - 1].ratio = '4:5';
      defaultTheme.ratio = '4:5'
      break;
    default:
      break;
  }
}

const ratioToNumber = computed(() => {
  let ratioArr = form.value.json5.cards[form.value.page - 1].ratio.split(':')
  return (parseInt(ratioArr[0]) / parseInt(ratioArr[1]))
})

// END: 圖片剪裁

const handleDelete = () => {
  form.value.json5.cards[form.value.page - 1].image = "";
};

const handlePreview = () => {
  router.push({
    name: "CardPreview",
    state: { content: JSON.stringify(form.value) },
  });
};

const onTitleSizeConfirm = ({ selectedOptions }) => {
  showTitleSizePicker.value = false;
  form.value.json5.cards[form.value.page - 1].titleSize =
    selectedOptions[0].text;
};

const onDescSizeConfirm = ({ selectedOptions }) => {
  showDescSizePicker.value = false;
  form.value.json5.cards[form.value.page - 1].descSize =
    selectedOptions[0].text;
};

const handleSubmit = async () => {
  let user_id = sessionStorage.getItem("uid");

  showLoadingToast({
    duration: 0,
    message: "名片上傳中...",
    forbidClick: true,
  });

  let cusCard = {
    card_title: form.value.title,
    show_cus: form.value.showNfc,
    cus_card: JSON.stringify(form.value),
  };

  let res = cardStore.updateCusCard(cusCard);

  if (res) {
    showSuccessToast("建立成功");
  } else {
    showFailToast("建立失敗");
  }

  // let res = await updateCusCard(cusCard);

  // if (res.code === 200) {
  //   cardStore.cusCard = cusCard;
  //   showSuccessToast("建立成功");
  // } else {
  //   showToast.fail("建立失敗");
  // }
  router.push("/card");
};
</script>

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

    <div class="content">
      <van-form @submit="handleSubmit">
        <van-cell-group inset>

          <van-cell class="bg-lightPink">
            <template #title>
              <h6 class="text-darkBlue"><strong>卡片設定</strong></h6>
            </template>
            <template #extra>
              <!-- <van-button size="small" class="ml-1 btn-moBlue" icon="tv-o" hairline @click="$router.push('/card/video')">教學影片</van-button> -->
              <van-button size="small" class="ml-1 btn-skyBlue" icon="tv-o" hairline
                @click="showMovie = true">教學影片</van-button>
              <van-button size="small" class="ml-1 btn-skyBlue" icon="eye-o" hairline
                @click="handlePreview">名片預覽</van-button>
            </template>
          </van-cell>

          <van-popup v-model:show="showMovie" class="p-3" closeable>
            <iframe width="375" height="215" src="https://www.youtube.com/embed/fjZsQ0Rh6yk" title="Utel電子名片教學"
              frameborder="0"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowfullscreen></iframe>
          </van-popup>

          <van-field v-model="form.title" label="標題文字" name="" input-align="right" error-message-align="right"
            placeholder="請輸入您在名片切換時顯示的文字" :rules="[{ required: true, message: '標題文字必填' }]" />
          <van-field label="是否顯示於感應名片" class="longText" input-align="right">
            <template #input>
              <van-switch v-model="form.showNfc" size="18px" active-color="#345068" inactive-color="#888888" />
            </template>
          </van-field>
        </van-cell-group>

        <van-cell-group inset class="mt-3">
          <keep-alive>
            <div id="app">

              <div class="bg-lightPink px-2 pt-3">
                <ul class="nav nav-tabs">
                  <li class="nav-item" v-for="(card, index) in form.json5.cards" :key="index"
                    @click="form.page = index + 1">
                    <button type="button" class="nav-link" :class="{ active: form.page === index + 1 }">
                      {{ index + 1 }}
                    </button>
                  </li>
                  <li class="nav-item" @click="addCard" v-if="form.json5.cards.length < 10">
                    <button type="button" class="nav-link">
                      <i class="fa fa-plus-circle"></i> 新增
                    </button>
                  </li>
                </ul>
              </div>

              <van-divider :style="{
                color: '#345068',
                borderColor: '#345068',
                padding: '0 16px',
              }"><strong>卡片設定</strong></van-divider>

              <van-field label="調整卡片順序" :border="false" v-if="form.json5.cards.length > 1">
                <template #button>
                  <van-button size="small" class="ml-1 btn-skyBlue" icon="arrow-left"
                    @click="moveCard(0, form.page)">前移</van-button>
                  <van-button size="small" class="ml-1 btn-skyBlue" icon="arrow"
                    @click="moveCard(1, form.page)">後移</van-button>
                  <van-button size="small" class="ml-1 btn-tomatoRed" icon="delete-o"
                    @click="delCard(form.page)"></van-button>
                </template>
              </van-field>

              <van-field v-model="form.json5.cards[form.page - 1].bgColor" label="卡片底色" id="vcard-bgColor"
                input-align="right" placeholder="請輸入卡片底色的色碼，如：#333333" :border="false"
                :rules="[{ required: true, message: '卡片底色色碼必填' }]">
                <template #button>
                  <input v-model="form.json5.cards[form.page - 1].bgColor" type="color" class="form-control-color" />
                </template>
              </van-field>

              <van-divider :style="{
                color: '#345068',
                borderColor: '#345068',
                padding: '0 16px',
              }"><strong>內容圖片設定</strong></van-divider>

              <van-field v-model="form.json5.cards[form.page - 1].ratio" :border="false">
                <template #input>
                  <van-uploader :after-read="afterRead" :max-count="1" name="cardimage" @delete="handleDelete">
                    <template v-if="form.json5.cards[form.page - 1].image.length > 0">
                      <div class="upload-main">
                        <img class="upload-img" :src="form.json5.cards[form.page - 1].image" alt="" />
                        <p class="ml-3 px-2 py-1 text-white bg-moBlue rounded-pill">
                          <i class="fa-solid fa-arrow-up"></i> 點擊更換圖片
                        </p>
                      </div>
                    </template>
                    <template v-else>
                      <div class="upload-main">
                        <img class="upload-img" src="@/assets/images/upload.jpg" />
                        <p class="ml-3 px-2 py-1 text-white bg-skyBlue rounded-pill">
                          <i class="fa-solid fa-arrow-up"></i> 請上傳圖片
                        </p>
                      </div>
                    </template>
                  </van-uploader>
                </template>
              </van-field>

              <van-divider :style="{
                color: '#345068',
                borderColor: '#345068',
                padding: '0 16px',
              }"><strong>卡片標題</strong></van-divider>

              <van-field v-model="form.json5.cards[form.page - 1].title" label="標題文字" id="vcard-title" input-align="right"
                placeholder="連結(需輸入完整網址,http://..,https://...)" :rules="[{ required: true, message: '請填寫卡片標題文字' }]" />

              <van-field v-model="form.json5.cards[form.page - 1].titleSize" is-link readonly label="標題文字大小"
                id="vcard-titleSize" input-align="right" placeholder="請輸入標題文字的色碼，如：#333333"
                @click="showTitleSizePicker = true" />
              <van-popup v-model:show="showTitleSizePicker" round position="bottom">
                <van-picker :columns="sizeColumns" @cancel="showTitleSizePicker = false" @confirm="onTitleSizeConfirm" />
              </van-popup>

              <van-field v-model="form.json5.cards[form.page - 1].titleColor" label="標題文字顏色" id="vcard-titleColor"
                input-align="right" placeholder="請輸入標題文字的色碼，如：#333333" :border="false"
                :rules="[{ required: true, message: '標題文字色碼必填' }]">
                <template #button>
                  <input v-model="form.json5.cards[form.page - 1].titleColor" type="color" class="form-control-color" />
                </template>
              </van-field>

              <van-divider :style="{
                color: '#345068',
                borderColor: '#345068',
                padding: '0 16px',
              }"><strong>卡片說明文字</strong></van-divider>

              <van-field v-model="form.json5.cards[form.page - 1].desc" label="說明文字" label-align="top" id="vcard-desc"
                type="textarea" rows="5" maxlength="250" placeholder="請填寫卡片說明文字" show-word-limit
                :rules="[{ required: true, message: '請填寫卡片說明文字' }]" />

              <van-field v-model="form.json5.cards[form.page - 1].descSize" is-link readonly label="說明文字大小"
                id="vcard-descSize" input-align="right" placeholder="請輸入說明文字的色碼，如：#333333"
                @click="showDescSizePicker = true" />
              <van-popup v-model:show="showDescSizePicker" round position="bottom">
                <van-picker :columns="sizeColumns" @cancel="showDescSizePicker = false" @confirm="onDescSizeConfirm" />
              </van-popup>

              <van-field v-model="form.json5.cards[form.page - 1].descColor" label="說明文字顏色" id="vcard-descColor"
                input-align="right" placeholder="請輸入說明文字的色碼，如：#333333" :rules="[{ required: true, message: '說明文字色碼必填' }]">
                <template #button>
                  <input v-model="form.json5.cards[form.page - 1].descColor" type="color" class="form-control-color" />
                </template>
              </van-field>

              <van-divider :style="{
                color: '#345068',
                borderColor: '#345068',
                padding: '0 16px',
              }"><strong>按鈕連結設定</strong></van-divider>

              <van-field label="新增按鈕" input-align="right" :border="false">
                <template #button>
                  <van-button size="small" class="ml-1 btn-tomatoRed" icon="add-o" @click="addBtn(form.page)">
                    <h6>新增按鈕</h6>
                  </van-button>
                  <van-button size="small" class="ml-1 btn-skyBlue" icon="share-o" @click="addShareBtn(form.page)">
                    <h6>新增分享按鈕</h6>
                  </van-button>
                </template>
              </van-field>

              <div class="cardCnt">
                <div class="card shadow" v-for="(btn, index) in form.json5.cards[form.page - 1].btns" :key="index">
                  <div class="card-header">
                    <van-field :label="`控制按鈕 ${index + 1}`" :border="false" class="bg-transparent">
                      <template #button>
                        <van-button size="small" class="bg-transparent border-0" icon="arrow-up"
                          @click="moveBtn(0, index)" v-if="form.json5.cards[form.page - 1].btns.length > 1"></van-button>
                        <van-button size="small" class="bg-transparent border-0" icon="arrow-down"
                          @click="moveBtn(1, index)" v-if="form.json5.cards[form.page - 1].btns.length > 1"></van-button>
                        <van-button size="small" class="bg-transparent border-0" icon="delete-o"
                          @click="delBtn(index)"></van-button>
                      </template>
                    </van-field>
                  </div>
                  <div class="card-body">
                    <van-field v-model="btn.text" :label="`按鈕 ${index + 1} 文字`" id="cardbtn-text-0" input-align="right"
                      placeholder="請填寫按鈕文字" :rules="[{ required: true, message: '請填寫按鈕文字' }]" />

                    <van-field v-model="btn.link" :label="`按鈕 ${index + 1} 連結`" id="cardbtn-link-0" input-align="right"
                      type="url" placeholder="連結(需輸入完整網址,http://..,https://...)"
                      :rules="[{ required: true, message: '請填寫按鈕連結' }]" />

                    <van-field v-model="btn.color" label="按鈕背景顏色" id="vcard-titleColor" input-align="right"
                      placeholder="請輸入標題文字的色碼，如：#333333" :rules="[{ required: true, message: '標題文字色碼必填' }]">
                      <template #button>
                        <input v-model="btn.color" type="color" class="colorCube" />
                      </template>
                    </van-field>

                    <van-field v-model="btn.btnHeight" label="按鈕大小" id="vcard-btnHeight" input-align="right"
                      :border="false" :rules="[{ required: true, message: '按鈕大小必填' }]">
                      <template #input>
                        <van-radio-group direction="horizontal" v-model="btn.btnHeight" checked-color="#345068">
                          <van-radio name="sm" @click="btn.btnHeight = 'sm'">sm</van-radio>
                          <van-radio name="md" @click="btn.btnHeight = 'md'">md</van-radio>
                        </van-radio-group>
                      </template>
                    </van-field>
                  </div>
                </div>
              </div>
            </div>
          </keep-alive>
        </van-cell-group>

        <van-sticky position="bottom">
          <div class="bottomBtnCnt">
            <van-button block class="btn-darkBlue" native-type="submit">名片確認 & 建立</van-button>
          </div>
        </van-sticky>
      </van-form>
    </div>
  </div>
  <van-overlay :show="crop.show" @click="crop.show = false" />
  <div class="cropper-section" v-if="crop.show">
    <div class="crop-area">
      <cropper class="cropper" ref="myCrop" :src="crop.img" :stencil-props="{
        aspectRatio: ratioToNumber,
      }" :auto-zoom="true" />
    </div>
    <div class="crop-btn">
      <div class="btn-group btn-group-sm" role="group" aria-label="Small button group">
        <button type="button" class="btn btn-outline-success" @click="setRatio(1)"
          :class="{ active: form.json5.cards[form.page - 1].ratio == '4:3' }">橫向4:3</button>
        <button type="button" class="btn btn-outline-success" @click="setRatio(2)"
          :class="{ active: form.json5.cards[form.page - 1].ratio == '1:1' }">方形1:1</button>
        <button type="button" class="btn btn-outline-success" @click="setRatio(3)"
          :class="{ active: form.json5.cards[form.page - 1].ratio == '4:5' }">直向4:5</button>
      </div>
      <div>
        <van-button type="primary" size="small" plain @click="onClose">取消</van-button>
        <van-button type="success" size="small" plain @click="onCrop">剪裁</van-button>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>

.edit {
  :deep(.van-van-field__control--min-height){
    min-height: 100px;
  }


  .colorCube,
  .colorCube:valid {
    appearance: none;
    background: 0 0;
    border: 1px solid #ced4da;
    height: 30px;
    padding: 0 2px;
    border-radius: 5px;
  }

  .flex-section {
    width: 100%;
  }

  :deep(.van-field__control) {
    justify-content: center;

    .upload-main {
      flex-direction: column;

      .upload-img {
        margin: 5px 0;
        width: 250px;
      }
    }

  }


  .nav-tabs {
    .nav-link {
      color: #4a677d;
      background-color: #fff;
      border-color: transparent;
      margin-right: 4px;
    }

    .nav-item.show .nav-link,
    .nav-link.active {
      color: #fff;
      background-color: #4a677d;
      border-color: #4a677d #4a677d #4a677d;
    }
  }

  .previewCnt {
    display: flex;
    justify-content: center;
    padding: 15px 0;
    background-color: #333;

    .card {
      width: 300px;
      border: none;
      // transform: scale(0.75);
      overflow: hidden;

      .card-body {
        padding: 15px;
      }
    }
  }

  .cardCnt {
    padding: 15px;

    .card {
      margin-bottom: 20px;

      .card-header {
        padding: 0;
        background-color: #ddd;
        border: none;
      }

      .card-body {
        padding: 10px 0;
      }
    }
  }
}

.cropper {
  height: 300px;
  // width: 300px;
  background: #ddd;
}

.cropper-section {
  margin: 0 auto;
  position: fixed;
  text-align: center;
  top: 50px;
  //   left: 0;
  height: 350px;
  width: 100%;
  max-width: 500px;
  background: #ddd;
  z-index: 8888;

  .crop-area {
    margin: 5 auto;
    width: 100%;
    height: 330px;
  }

  .crop-btn {
    text-align: center;
    display: flex;
    justify-content: space-between;
    background-color: #fff;
  }
}

</style>
