<script setup lang="ts">
import { useSimpleDataLoader } from '@/composeable/SimpleDataLoader';
import { useRouter } from 'vue-router';
import ImageSwiper from '@/components/small/ImageSwiper.vue';
import Swiper1 from '@/assets/images/Home/swiper1.jpg';
import Swiper2 from '@/assets/images/Home/swiper2.jpg';
import Card1 from '@/assets/images/Home/Card/1.jpg';
import Card2 from '@/assets/images/Home/Card/2.jpg';
import Card3 from '@/assets/images/Home/Card/3.jpg';
import Card4 from '@/assets/images/Home/Card/4.jpg';
import Card5 from '@/assets/images/Home/Card/5.jpg';
import Card6 from '@/assets/images/Home/Card/6.jpg';
import Card7 from '@/assets/images/Home/Card/7.jpg';
import Card8 from '@/assets/images/Home/Card/8.jpg';
import { computed, onMounted, ref } from 'vue';
import SimplePopup from '@/components/SimplePopup.vue';
import { DynamicForm, type IDynamicFormOptions, type IDynamicFormRef } from '@imengyu/vue-dynamic-form';
import IndexContent from '@/api/introduction/IndexContent';
import { SettingsUtils } from '@imengyu/imengyu-utils';
import Tab from '@/components/small/Tab.vue';
import { useHandleWindowKey } from '@/composeable/HandleWindowKey';

const router = useRouter();
const defaultCards = [Card1, Card2, Card3, Card4, Card5, Card6, Card7, Card8];
const mainPageDataDefault = {
  title: 'Default',
  buttons: [
    { 
      image: Card1,
      title: '保护概况',
      id: 1,
    },
    { 
      image: Card2,
      title: '闽南精神',
      id: 2,
      },
    { 
      image: Card3,
      title: '古早话仙',
      id: 3,
    },
    { 
      image: Card4,
      title: '民俗风情',
      id: 4,
      },
    { 
      image: Card5,
      title: '保护传承',
      id: 5,
    },
    { 
      image: Card6,
      title: '闽南时尚',
      id: 6,
    },
    { 
      image: Card7,
      title: '文化之旅',
      id: 7,
    },
    { 
      image: Card8,
      title: '厝边记忆',
      id: 8,
    },
  ],
  swiper: [
    {
      image: Swiper1,
      title: ''
    },
    {
      image: Swiper2,
      title: ''
    },
  ],
};
const mainPageHasCustomConfig = ref(false);
const mainPageCurrentShowConfig = ref(false);
const mainPageCustomConfigData = useSimpleDataLoader(async () => {
  const deviceCode = SettingsUtils.getSettings('deviceCode', '');
  if (deviceCode) {
    const config = await IndexContent.getTerminalConfig(deviceCode);
    mainPageHasCustomConfig.value = true;
    mainPageCurrentShowConfig.value = true;
    return {
      title: config.name,
      swiper: config.images.map((item) => ({
        image: item,
        title: ''
      })),
      buttons: config.pageJson.map((item, i) => ({
        image: item.logo || defaultCards[i],
        title: item.title,
        page: item.page,
        id: i,
      })),
    };
  } else return mainPageDataDefault;
});
const mainPageData = computed(() => {
  if (mainPageHasCustomConfig.value && mainPageCurrentShowConfig.value) {
    return mainPageCustomConfigData.content.value;
  } else return mainPageDataDefault;
});


const showBindDeviceCode = ref(false);
const bindDeviceCodeFormModel = ref({
  userName: '',
  deviceCode: '',
});
const bindDeviceCodeFormStatus = ref('');
const bindDeviceCodeFormRef = ref<IDynamicFormRef>();
const bindDeviceCodeFormOptions = ref<IDynamicFormOptions>({
  formLabelCol: { span: 0 },
  formWrapperCol: { span: 24 },
  formRules: {
    userName: [
      { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    deviceCode: [
      { required: true, message: '请输入机器码', trigger: 'blur' }
    ],
  },
  formItems: [
    {
      type: 'base-text',
      label: '',
      name: 'userName',
      additionalProps: { placeholder: '请输入用户名' }
    },
    {
      type: 'base-text',
      label: '',
      name: 'deviceCode',
      additionalProps: { placeholder: '请输入机器码' }
    },
  ],
});

async function handleBindDeviceCode() {
  bindDeviceCodeFormStatus.value = '设置中请稍等...';
  try {
    await IndexContent.bindMachineCode(bindDeviceCodeFormModel.value.userName, bindDeviceCodeFormModel.value.deviceCode);
    bindDeviceCodeFormStatus.value = '绑定成功，正在刷新请稍等...';
    SettingsUtils.setSettings('deviceCode', bindDeviceCodeFormModel.value.deviceCode);
    setTimeout(() => {
      mainPageCustomConfigData.loadData(undefined, true);
      showBindDeviceCode.value = false;
    }, 1000);
  } catch (e) {
    bindDeviceCodeFormStatus.value = '绑定失败，' + e;
  }
}
function handleClick(item: any) {
  if (item.page) {
    const p = item.page.split('?');
    const query : Record<string, any> = {};
    p[1].split('&').forEach((item: string) => {
      const j = item.split('=');
      query[j[0]] = j[1];
    });
    router.push({ name: p[0], query });
  } else
    router.push({ name: 'Content', query: { tab: item.id } });
}

useHandleWindowKey('ContextMenu', () => {
  showBindDeviceCode.value = true;
});


/* onMounted(() => {
  SettingsUtils.setSettings('deviceCode', '1122');
}) */
</script>

<template>
  <main class="main-content">
    <div class="main-bg absolute">
      <ImageSwiper :items="mainPageData?.swiper ?? []" :autoplay="4000" :showAddons="false" :tabindex="-1">
        <template #item="{ item }">
          <img :src="item.image" alt="">
        </template>
      </ImageSwiper>
    </div>
    <div class="content absolute d-flex flex-col">
      <div class="invisible-button">
        <div v-if="mainPageHasCustomConfig" class="d-flex flex-row">
          <Tab :modelValue="mainPageCurrentShowConfig? 1 : 0" :tabs="[
            { label: '闽南文化' },
            { label: mainPageCustomConfigData.content.value?.title || '自定义' },
          ]" @update:modelValue="(v) => mainPageCurrentShowConfig = v == 1" />
        </div>
        <div v-else class="main-any-button box" @click="showBindDeviceCode=true" />
      </div>

      <img v-if="mainPageData?.title === 'Default'" src="@/assets/images/Home/title.png" alt="" class="main-title">
      <div v-else class="main-title">{{ mainPageData?.title }}</div>

      <div class="main-card-space" />
      <div class="main-card-list">
        <div 
          v-for="(item, index) in mainPageData?.buttons ?? []"
          :key="index"
          :tabindex="1"
          :style="{
            backgroundImage: `url(${item.image})`
          }"
          class="main-card round active"
          @click="handleClick(item)"
        >
          {{ item.title }}
        </div>
      </div>
    </div>
    <SimplePopup 
      :show="showBindDeviceCode"
      @update:show="(v) => showBindDeviceCode = v"
    >
      <div class="bind-device">
        <h1 class="title">绑定机器码</h1>
        <DynamicForm 
          ref="bindDeviceCodeFormRef"
          :model="bindDeviceCodeFormModel"
          :options="bindDeviceCodeFormOptions" 
          @submit="handleBindDeviceCode"
        />
        <p v-if="bindDeviceCodeFormStatus" class="text-danger">{{ bindDeviceCodeFormStatus }}</p>
        <div class="d-flex flex-row p-3 pl-0 pr-0 justify-between gap-ss">
          <button class="flex-one" @click="showBindDeviceCode=false">取消</button>
          <button class="flex-one" @click="bindDeviceCodeFormRef?.submit()">确定</button>
        </div>
      </div>
    </SimplePopup>
  </main>
</template>

<style lang="scss" scoped>
.content {
  padding-left: 6%;
  padding-right: 6%;
  padding-top: 6%;
  padding-bottom: 6%;
}
.main-title {
  width: 40%;
  color: #fff;
  font-size: 3rem;
}
.main-card-space {
  height: 50%;
}
.bind-device  {
  background-color: #fff;
  border-radius: 1rem;
  padding: 1.5rem;
  width: 400px;

  h1 {
    font-size: 1rem;
    margin-bottom: 2rem;
    text-align: center;
  }
}

.main-card-list {
  position: relative;
  height: 45%;
  min-height: 30vh;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  grid-gap: 20px;
  font-size: 26px;

  .main-card {
    font-size: 3cqh;
    padding: 0 15%;
    color: var(--color-primary);
  }
}
.invisible-button {
  position: absolute;
  right: 1rem;
  top: 1rem;
  min-width: 3rem;
  height: 3rem;

  .box {
    width: 3rem;
    height: 3rem;
  }
}

@media (max-width: 800px) {
  .content {
    padding-left: 10%;
    padding-right: 2%;
  }
}
@media (max-height: 400px) {
  .main-card-space {
    height: 16%;
  }
}
@media (max-height: 600px) {
  .content {
    padding-top: 7%;
    padding-bottom: 1%;
  }
  .main-card-space {
    height: 24%;
  }
}

</style>
