<template>
  <ImagePreview  style="width:100%;height:" v-if="isShowImagePreview" :globalImagePreviewUrl="globalImagePreviewUrl" @closeImagePreview="closeImagePreview"></ImagePreview>
  <template v-if="haveTab">
    <a-tabs v-model:activeKey="selectTab">
      <a-tab-pane v-for="(tab, tabIndex) in showList" :key="tabIndex" :tab="tab.label">
        <a-descriptions 
          :column="2" 
          bordered 
          :contentStyle="{
            'text-align': 'center',
            'min-width': '250px',
            'word-break': 'break-all'
          }">
          <template v-for="(item, index) in tab.children" :key="index">
            <template v-if="item.infoShowValue">
              <a-descriptions-item v-if="item.component === 'ImageUpload'" :label="item.label">
                <a-image
                  width="100px"
                  height="100px"
                  :preview="false"
                  :src="`${item.componentProps.server}/${item.infoShowValue}`"
                  @click="handlerPreviewImage(item.componentProps.server+'/'+item.infoShowValue)"
                ></a-image>
              </a-descriptions-item>
              <a-descriptions-item v-else-if="item.component === 'VideoUpload'" :label="item.label">
                <template v-for="(videoItem, videoIndex) in item.infoShowValue" :key="videoIndex">
                  <img v-if="videoItem" style="width: 100px; height: 100px; cursor: pointer;" src="./video.png" @click="handlePreview(item, videoItem)" alt="">
                </template>
              </a-descriptions-item>
              <a-descriptions-item v-else :label="item.label">
                <div>{{ item.infoShowValue}}</div>
              </a-descriptions-item>
            </template>
          </template>
        </a-descriptions>
      </a-tab-pane>
    </a-tabs>
  </template>
  
  <template v-else>
    <a-descriptions 
      :column="2" 
      bordered
      :contentStyle="{
        'text-align': 'center',
        'min-width': '250px',
        'word-break': 'break-all'
      }">
      <template v-for="(item, index) in showList" :key="index">
        <template v-if="item.infoShowValue">
          <a-descriptions-item v-if="item.component === 'ImageUpload'" :label="item.label">
            <template  v-for="(imageItem, imageIndex) in item.infoShowValue" :key="imageIndex" >
              <a-image
                v-if="imageItem"
                width="100px"
                height="100px"
                :src="`${item.componentProps.server}/${imageItem}`"
              ></a-image>
            </template>
          </a-descriptions-item>
          <a-descriptions-item v-else-if="item.component === 'VideoUpload'" :label="item.label">
            <template v-for="(videoItem, videoIndex) in item.infoShowValue" :key="videoIndex">
              <img v-if="videoItem" style="width: 100px; height: 100px; cursor: pointer;" src="./video.png" @click="handlePreview(item,videoItem)" alt="">
            </template>
          </a-descriptions-item>
          <a-descriptions-item v-else :label="item.label">{{ item.infoShowValue }}</a-descriptions-item>
        </template>
      </template>
    </a-descriptions>
    <a-table v-if="subTableData" :columns="columns" :data-source="props.data.infoUseSubTableData" :pagination="false"></a-table>
  </template>
  <Modal :open="previewOpen" :title="previewTitle" :footer="null" @cancel="handleCancel" :zIndex="1001">
    <video :src="previewVideo" class="video-player" controls muted autoplay></video>
  </Modal>
</template>

<script setup lang="tsx">
import { defineProps, watch, ref, defineEmits, onMounted } from "vue"
import ShowCardGroupItem from './ShowCardGroupItem/index.vue'
import { Modal } from 'ant-design-vue'

import { storeToRefs } from 'pinia';
import ImagePreview from "@/components/Upload/src/components/image_preview.vue";
import { userFormFileStore } from '@/store/modules/formFileUrl';

const props = defineProps(["open","data"])
const emits = defineEmits(["update:open"])
const showList = ref<any[]>([])
const selectTab = ref(0)
const haveTab = ref(false)
const previewVideo = ref("")
const previewOpen = ref(false)
const previewTitle = ref("")
const subTableData = ref(null)
const columns = ref([])
onMounted(() => {
  console.log('props.data',props.data)
  props.data.tab.forEach(item => {
    if(item.component === 'Tabs'){
      haveTab.value = true
      item.componentProps.options.forEach((tab, tabIndex) => {
        showList.value.push({
          label: tab.label,
          key: tabIndex,
          children: []
        })
        tab.children.forEach(childItem => {
          if(childItem.columns && childItem.type !== 'subTable'){
            childItem.columns.forEach(childColumn => {
              if(childColumn.children){
                childColumn.children.forEach(child => {
                  showList.value[tabIndex].children.push({
                    ...child, 
                    infoShowValue: props.data.infoUseMainTableData[child.field]
                  })
                })
              }else{
                showList.value[tabIndex].children.push({
                  ...childColumn,
                  infoShowValue: props.data.infoUseMainTableData[childColumn.field]
                })
              }
            })
          }else if (childItem.component === 'CardGroup'){
            setCardGroupItem(childItem, tabIndex)
          }else if(childItem.component === 'RadioGroup') {
            showList.value[tabIndex].children.push({
              ...childItem,
              infoShowValue: getOptionLabel(childItem)
            })
          }else if(['ImageUpload','VideoUpload'].includes(childItem.component)){
            showList.value[tabIndex].children.push({
              ...childItem,
              infoShowValue: props.data.infoUseMainTableData[childItem.field]? props.data.infoUseMainTableData[childItem.field].split(','): null
            })
          }else if(childItem.component !== 'InputGuid'){
            showList.value[tabIndex].children.push({
              ...childItem,
              infoShowValue: props.data.infoUseMainTableData[childItem.field]
            })
          }
        })
      })
    }else{
      if(item.columns && item.type !== 'subTable'){
        item.columns.forEach(childColumn => {
          if(childColumn.children){
            childColumn.children.forEach(child => {
              showList.value.push({
                ...child, 
                infoShowValue: props.data.infoUseMainTableData[child.field]
              })
            })
          }else{
            showList.value.push({
              ...childColumn,
              infoShowValue: props.data.infoUseMainTableData[childColumn.field]
            })
          }
        })
      }else if (item.component === 'CardGroup'){
        noTabsSetCardGroupItem(item, tabIndex)
      }else if(['RadioGroup', 'Select'].includes(item.component)) {
        showList.value.push({
          ...item,
          infoShowValue: getOptionLabel(item)
        })
      }else if(item.component === 'Grid' && item.type === 'subTable') {
        subTableData.value = item,
        // columns
        item.columns[0].children.forEach(child => {
          columns.value.push({
            title: child.label,
            dataIndex: child.field,
            key: child.field,
          })
        })
      }else if(['ImageUpload','VideoUpload'].includes(item.component)){
        showList.value.push({
          ...item,
          infoShowValue: props.data.infoUseMainTableData[item.field]? props.data.infoUseMainTableData[item.field].split(','): null
        })
      }else if(item.component !== 'InputGuid'){
        showList.value.push({
          ...item,
          infoShowValue: props.data.infoUseMainTableData[item.field]
        })
      }
    }
  })
})
const getOptionLabel = (item) => {
  let result = null
  let value = props.data.infoUseMainTableData[item.field]
  item.componentProps.options.forEach(item => {
    if(item.value == value){
      result = item.label
    }
  })
  return result
}
const getCardGroupShowChard = (cardGroupItem) => {
  let result = []
  let value = props.data.infoUseMainTableData[cardGroupItem.field]
  cardGroupItem.componentProps.options.forEach(item => {
    if(item.value == value){
      result = item.children
    }
  })
  return result
}
const setCardGroupItem = (item, index) => {
  showList.value[index].children.push({
    ...item,
    infoShowValue: getOptionLabel(item)
  })
  getCardGroupShowChard(item).forEach(childItem => {
    if(childItem.component === 'CardGroup'){
      setCardGroupItem(childItem, index)
    }else{
      showList.value[index].children.push({
        ...childItem,
        infoShowValue: props.data.infoUseMainTableData[childItem.field]
      })
    }
  })
}
const noTabsSetCardGroupItem = (item, index) => {
  showList.value.push({
    ...item,
    infoShowValue: getOptionLabel(item)
  })
  getCardGroupShowChard(item).forEach(childItem => {
    if(childItem.component === 'CardGroup'){
      noTabsSetCardGroupItem(childItem, index)
    }else{
      showList.value.push({
        ...childItem,
        infoShowValue: props.data.infoUseMainTableData[childItem.field]
      })
    }
  })
}
// const closeModal = () => {
//   emits('update:open', false)
//   showList.value = []
//   columns.value = []
//   subTableData.value = null
// }
const handlePreview = (item,videoItem) => {
  previewVideo.value = `${item.componentProps.server}/${videoItem}`;
  previewOpen.value = true;
  previewTitle.value = videoItem
};
const handleCancel = () => {
  previewVideo.value = '';
  previewOpen.value = false;
  previewTitle.value = '';
};

// 
function handlerPreviewImage(url):void{
  globalImagePreviewUrl.value = url+"?"+Math.random();
  formFileStore.setUrl(url+"?"+Math.random());
}


// 图片预览
const isShowImagePreview = ref<Boolean>(false);
const closeImagePreview = ()=>{
  isShowImagePreview.value = false;
}
const globalImagePreviewUrl=ref<String>();
const formFileStore = userFormFileStore();
const formFileState = storeToRefs(formFileStore);
watch(formFileState.url, (newValue, oldValue) => {
  // isShowImagePreview.value = true;
  // globalImagePreviewUrl.value = newValue;
});


// 图片转Base64
function handlerConvertImageToBase64(url, callback) {
    var img = new Image();
    img.crossOrigin = 'Anonymous'; // 处理跨域问题
    img.onload = function () {
      var canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      var dataURL = canvas.toDataURL('image/jpeg'); // 或者使用 'image/jpeg' 来获得 JPEG 格式的 base64 字符串
      callback(dataURL);
    };
    img.src = url;
  }
</script>

<style lang="scss" scoped>
.video-player{
  width:500px;
  margin:10px;
}
</style>
