<template>
  <div
    class="table-select"
    :class="isDarkTheme ? '' : 'bright'"
  >
    <span class="title">{{ title }}</span>
    <div class="close-btn"><i class="iconfont icon-pop-ups_shut-down" @click="$emit('cancle')"></i></div>

    <div class="material-tab">
      <a
        v-if="selectableType.includes('image')"
        class="material-tab-item"
        @click.prevent="currentMaterialType = 'image'"
      >
        <span :class="{ active: currentMaterialType === 'image' }" class="text">
          {{ $i18n.t(`gather.image`) }}
        </span>
        <div v-if="currentMaterialType === 'image'" class="bottom-line"></div>
      </a>
      <a
        v-if="selectableType.includes('pano')"
        class="material-tab-item"
        @click.prevent="currentMaterialType = 'pano'"
      >
        <span :class="{ active: currentMaterialType === 'pano' }" class="text">
          {{ $i18n.t(`gather.panorama`) }}
        </span>
        <div v-if="currentMaterialType === 'pano'" class="bottom-line"></div>
      </a>
      <a
        v-if="selectableType.includes('audio')"
        class="material-tab-item"
        @click.prevent="currentMaterialType = 'audio'"
      >
        <span :class="{ active: currentMaterialType === 'audio' }" class="text">
          {{ $i18n.t(`gather.audio`) }}
        </span>
        <div v-if="currentMaterialType === 'audio'" class="bottom-line"></div>
      </a>
      <a
        v-if="selectableType.includes('video')"
        class="material-tab-item"
        @click.prevent="currentMaterialType = 'video'"
      >
        <span :class="{ active: currentMaterialType === 'video' }" class="text">
          {{ $i18n.t(`gather.video`) }}
        </span>
        <div v-if="currentMaterialType === 'video'" class="bottom-line"></div>
      </a>
      <a
        v-if="selectableType.includes('3D')"
        class="material-tab-item"
        @click.prevent="currentMaterialType = '3D'"
      >
        <span :class="{ active: currentMaterialType === '3D' }" class="text">
          {{ $i18n.t(`gather.scene`) }}
        </span>
        <div v-if="currentMaterialType === '3D'" class="bottom-line"></div>
      </a>
    </div>
    
    <div
      class="filter"
      :class="{active: isSearchKeyInputActive}"
    >
      <input
        type="text"
        :placeholder="$i18n.t('gather.keywords')"
        v-model="searchKey"
        @focus="isSearchKeyInputActive = true"
        @blur="isSearchKeyInputActive = false"
      />
      <i v-if="!searchKey" class="iconfont icon-editor_search search-icon" />
      <i v-if="searchKey" @click="searchKey=''" class="iconfont icontoast_red clear-icon"></i>
    </div>

    <MaterialList
      v-if="selectableType.includes('pano')"
      v-show="currentMaterialType === 'pano'"

      :isDarkTheme="isDarkTheme"
      
      :currentMaterialType="currentMaterialType"
      :materialType="'pano'"
      
      :tableHeaderKeyList="['icon', 'name']"

      :isMultiSelection="isMultiSelection"
      :select="select"

      :searchKey="searchKey"

      :canUpload="true"
      :fileInputCustomCheck="checkPanoFileInput"
      :fileUploadLongPollingCb="panoUploadLongPolling"
      :fileUploadLongPollingStatusText="$i18n.t(`gather.cutting`)"
      :fileInputBtnTip="$i18n.t(`gather.pano_size`)"
      :fileInputFailString="$i18n.t(`gather.pano_fail`)"
      :fileInputLimitFailStr="$i18n.t(`gather.pano_limit`)"
      :fileInputAcceptType="'image/jpeg'"
      :fileInputMediaType="'image'"
      :fileInputLimit="120"

      @need-clear-filter="() => {searchKey = ''}"
    >
      <template
        v-slot:materialUploadSuccessIcon="slotProps"
      >
        <img
          :src="slotProps.uploadInfo.successInfo[slotProps.tableItemStructure.key] + (Number(slotProps.uploadInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
      <template
        v-slot:materialUploadingIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-image@2x.png"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialUploadFailIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-image@2x.png"
          style="object-fit: contain;"
        |  alt=""
        >
      </template>
      <template
        v-slot:materialIcon="slotProps"
      >
        <img
          :src="slotProps.materialInfo[slotProps.tableItemStructure.key] + (Number(slotProps.materialInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
    </MaterialList>

    <MaterialList
      v-if="selectableType.includes('image')"
      v-show="currentMaterialType === 'image'"

      :isDarkTheme="isDarkTheme"

      :currentMaterialType="currentMaterialType"
      :materialType="'image'"
      
      :tableHeaderKeyList="['icon', 'name']"
      
      :isMultiSelection="isMultiSelection"
      :select="select"

      :searchKey="searchKey"

      :canUpload="true"
      :fileInputBtnTip="$i18n.t(`gather.img_size`)"
      :fileInputFailString="$i18n.t(`gather.img_fail`)"
      :fileInputLimitFailStr="$i18n.t(`gather.img_limit`)"
      :fileInputAcceptType="'image/png,image/jpeg'"
      :fileInputMediaType="'image'"
      :fileInputLimit="10"

      @need-clear-filter="() => {searchKey = ''}"
    >
      <template
        v-slot:materialUploadSuccessIcon="slotProps"
      >
        <img
          :src="slotProps.uploadInfo.successInfo[slotProps.tableItemStructure.key] + (Number(slotProps.uploadInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
      <template
        v-slot:materialUploadingIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-image@2x.png"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialUploadFailIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-image@2x.png"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialIcon="slotProps"
      >
        <img
          :src="slotProps.materialInfo[slotProps.tableItemStructure.key] + (Number(slotProps.materialInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
    </MaterialList>

    <MaterialList
      v-if="selectableType.includes('audio')"
      v-show="currentMaterialType === 'audio'"

      :isDarkTheme="isDarkTheme"

      :currentMaterialType="currentMaterialType"
      :materialType="'audio'"
      
      :tableHeaderKeyList="['ossPath', 'name']"
      
      :isMultiSelection="isMultiSelection"
      :select="select"

      :searchKey="searchKey"

      :canUpload="true"
      :fileInputBtnTip="$i18n.t(`gather.audio_size`)"
      :fileInputFailString="$i18n.t(`gather.audio_fail`)"
      :fileInputLimitFailStr="$i18n.t(`gather.audio_limit`)"
      :fileInputAcceptType="'audio/mp3'"
      :fileInputMediaType="'audio'"
      :fileInputLimit="20"

      @need-clear-filter="() => {searchKey = ''}"
    >
      <template
        v-slot:materialUploadSuccessIcon="slotProps"
      >
        <AudioIconCanPlay
          class="audio-player"
          :vKey="slotProps.uploadInfo.successInfo.id"
          :idleft="`_${$randomWord(true, 8, 8)}`"
          :idright="`_${$randomWord(true, 8, 8)}`"
          :myAudioUrl="slotProps.uploadInfo.successInfo.ossPath"
        />
      </template>
      <template
        v-slot:materialUploadingIcon
      >
        <img
          :src="require('@/assets/images/icons/upload-file-type-icon-audio@2x.png')"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialUploadFailIcon
      >
        <img
          :src="require('@/assets/images/icons/upload-file-type-icon-audio@2x.png')"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialIcon="slotProps"
      >
        <AudioIconCanPlay
          class="audio-player"
          :vKey="slotProps.materialInfo.id"
          :idleft="`_${$randomWord(true, 8, 8)}`"
          :idright="`_${$randomWord(true, 8, 8)}`"
          :myAudioUrl="slotProps.materialInfo.ossPath"
        />
      </template>
    </MaterialList>

    <MaterialList
      v-if="selectableType.includes('video')"
      v-show="currentMaterialType === 'video'"

      :isDarkTheme="isDarkTheme"

      :currentMaterialType="currentMaterialType"
      :materialType="'video'"
      :materialItemCustomProcess="(item) => {item.icon = process.env.VUE_APP_ORIGIN == 'aws' ? item.icon : (item.ossPath + '?x-oss-process=video/snapshot,t_0,f_jpg,w_89,h_50,m_fast,ar_auto');}"

      :tableHeaderKeyList="['icon', 'name']"
      
      :isMultiSelection="isMultiSelection"
      :select="select"

      :searchKey="searchKey"

      :canUpload="true"
      :fileInputBtnTip="$i18n.t(`gather.video_size`)"
      :fileInputFailString="$i18n.t(`gather.video_fail`)"
      :fileInputLimitFailStr="$i18n.t(`gather.video_limit`)"
      :fileInputAcceptType="'video/mp4'"
      :fileInputMediaType="'video'"
      :fileInputLimit="200"

      @need-clear-filter="() => {searchKey = ''}"
    >
      <template
        v-slot:materialUploadSuccessIcon="slotProps"
      >
        <img
          :src="slotProps.uploadInfo.successInfo[slotProps.tableItemStructure.key] + (Number(slotProps.uploadInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
      <template
        v-slot:materialUploadingIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-video@2x.png"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialUploadFailIcon
      >
        <img
          src="@/assets/images/icons/upload-file-type-icon-video@2x.png"
          style="object-fit: contain;"
          alt=""
        >
      </template>
      <template
        v-slot:materialIcon="slotProps"
      >
        <img
          :src="slotProps.materialInfo[slotProps.tableItemStructure.key] + (Number(slotProps.materialInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
    </MaterialList>

    <MaterialList
      v-if="selectableType.includes('3D')"
      v-show="currentMaterialType === '3D'"

      :isDarkTheme="isDarkTheme"

      :currentMaterialType="currentMaterialType"
      :materialType="'3D'"
      :workId="workId"

      :tableHeaderKeyList="['thumb', 'sceneName']"

      :isMultiSelection="isMultiSelection"
      :select="select"

      :searchKey="searchKey"

      @need-clear-filter="() => {searchKey = ''}"
    >
      <template
        v-slot:materialIcon="slotProps"
      >
        <img
          :src="slotProps.materialInfo[slotProps.tableItemStructure.key] + (Number(slotProps.materialInfo.fileSize) > 512 ? $imgsuffix : ``)"
          alt=""
        />
      </template>
    </MaterialList>

    <div class="btns">
      <button
        class="ui-button"
        :class="isDarkTheme ? 'deepcancel' : 'cancel'"
        @click="$emit('cancle')"
      >{{ $i18n.t("gather.cancel") }}</button>
      <button class="ui-button submit" :class="{ disable: !select.length }" @click="onClickComfirm">
        {{ $i18n.t("gather.comfirm"), }}
      </button>
    </div>
  </div>
</template>

<script>
import { mapMutations, } from "vuex";
import MaterialList from "./materialListInMaterialSelector.vue";
import AudioIconCanPlay from "@/components/audio/indexForEditor.vue";
import { getImgWH, changeByteUnit } from "@/utils/file";
import { debounce } from "@/utils/other.js"
import {
  checkMStatus,
} from "@/api";

export default {
  components: {
    MaterialList,
    AudioIconCanPlay,
  },
  props: {
    isDarkTheme: {
      type: Boolean,
      default: true,
    },
    title: {
      default: '',
      type: String
    },
    selectableType: {
      type: Array,
      default: function() {
        return [
          'image',
          'pano',
          'audio',
          'video',
          '3D',
        ]
      },
    },
    initialMaterialType: {
      type: String,
      default: 'image',
    },
    isMultiSelection: {
      type: Boolean,
      default: false,
    },
    workId: {
      type: String,
      default: '',
    },
  },
  data () {
    return {
      select: [],
      isSearchKeyInputActive: false,
      searchKey: '', // 搜索关键词
      latestUsedSearchKey: '',

      currentMaterialType: this.initialMaterialType,
    }
  },
  watch: {
  },
  methods: {
    ...mapMutations([
      'clearUploadStatusLists',
    ]),
    async checkPanoFileInput(eachFile, i) {
      let WHRate = null
      try {
        const { width, height } = await getImgWH(eachFile)
        WHRate = width / height
      } catch (e) {
        console.error('获取图像宽高失败：', e)
        setTimeout(() => {
          this.$msg({
            message: `“${eachFile.name}”${this.$i18n.t(`gather.pano_fail`)}`,
            type: "warning",
          });
        }, i * 100);
        return false
      }
      if (WHRate !== 2) {
        console.log('宽高比不对！');
        setTimeout(() => {
          this.$msg({
            message: `“${eachFile.name}”${this.$i18n.t(`gather.pano_fail`)}`,
            type: "warning",
          });
        }, i * 100);
        return false
      } else {
        console.log(WHRate);
        return true
      }
    },
    panoUploadLongPolling(uploadStatusList) {
      let needPollingTaskList = uploadStatusList.filter((item) => item.status === 'LOADING' && item.ifKnowProgress === false);
      if (needPollingTaskList.length > 0) {
        checkMStatus(
          {
            ids: needPollingTaskList.map((item) => item.backendId),
            islongpolling: true,
          },
          (res) => {
            // 1切图中，2失败，3成功
            res.data.forEach(eachRes => {
              if (eachRes.status === 2) {
                const index = uploadStatusList.findIndex(eachTask => eachTask.backendId === eachRes.id)
                if (index >= 0) {
                  const targetItem = uploadStatusList[index]
                  targetItem.status = 'FAIL'
                  targetItem.statusText = this.$i18n.t(`gather.material_cutting_fail`)
                  targetItem.ifKnowProgress = true
                }
              } else if (eachRes.status === 3) {
                const index = uploadStatusList.findIndex(eachTask => eachTask.backendId === eachRes.id)
                if (index >= 0) {
                  const targetItem = uploadStatusList[index]
                  targetItem.status = 'SUCCESS'
                  if (eachRes.fileSize) {
                    eachRes.fileSize = changeByteUnit(Number(eachRes.fileSize));
                  } else {
                    eachRes.fileSize = ''
                  }
                  targetItem.successInfo = eachRes
                }
              }
            });
          }
        );
      }
    },
    onClickComfirm: debounce(function () {
      this.$emit('submit', this.select)
    }, 250),
  },
  mounted() {
    this.clearUploadStatusLists()
  },
}
</script>

<style lang="less" scoped>
.table-select {
  position: absolute;
  z-index: 3;
  left: 50%;
  top: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 600px;
  height: 730px;
  background: #1A1B1D;
  border-radius: 4px;
  border: 1px solid #404040;
  padding: 26px;

  .title {
    font-size: 18px;
    color: rgba(255, 255, 255, 0.6);
  }

  .close-btn {
    display: inline-block;
    position: absolute;
    top: 26px;
    right: 20px;
    font-size: 12px;
    color: #969799;
    cursor: pointer;
    padding: 6px;
  }
  .material-tab {
    margin-top: 35px;

      > .material-tab-item {
      display: inline-block;
      margin-right: 20px;
      position: relative;
      cursor: pointer;

      > .text {
        font-size: 14px;
        font-family: MicrosoftYaHei;
        color: rgba(255, 255, 255, 0.6);
        &.active {
          color: #fff;
        }
      }

      > .bottom-line {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: -4px;
        width: 16px;
        height: 2px;
        background: #0076F6;
        border-radius: 1px;
      }
    }
  }

  .filter {
    margin-top: 28px;
    width: 100%;
    height: 36px;
    background: #252526;
    border-radius: 2px;
    border: 1px solid #404040;
    position: relative;
    &.active {
      border: 1px solid @color;
    }
    > input {
      box-sizing: border-box;
      width: calc(100% - 42px);
      height: 100%;
      border: none;
      padding-left: 16px;
      background: transparent;
      color: #fff;
      outline: none;
    }
    > input::placeholder,
    textarea::placeholder {
      font-size: 14px;
      color: #505050 !important;
    }

    > .search-icon {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 18px;
      color: #404040;
      font-size: 20px;
    }
    > .clear-icon {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 18px;
      color: #404040;
      font-size: 20px;
      cursor: pointer;
    }
  }

  .btns {
    position: absolute;
    right: 26px;
    bottom: 26px;
    button:first-child {
      margin-right: 16px;
    }
  }
}

.table-select.bright {
  border: 1px solid #EBEDF0;
  background: #fff;
  .title {
    color: #323233;
  }

  .close-btn {
  }
  .material-tab {

      > .material-tab-item {
      > .text {
        color: #969799;
        &.active {
          color: #323233;
        }
      }

      > .bottom-line {
      }
    }
  }

  .filter {
    background: #F7F8FA;
    border: 1px solid #EBEDF0;

    > input {
      color: #323233;
    }
    > input::placeholder,
    textarea::placeholder {
      font-size: 14px;
      color: #C8C9CC !important;
    }
    
    > .search-icon {
      color: #C8C9CC;
    }
    > .clear-icon {
      color: #C8C9CC;
    }
  }

  .btns {
  }
}
</style>