<script setup lang="ts">
import { reactive, ref, watch, inject, Ref, onMounted } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture, Search } from '@element-plus/icons-vue'
import { getVideoAssets, videoDetailCreate, uploadFile, checkAsset, postVideo } from '../api/index'
import emitter from '/@/utils/emitter'
import { storeToRefs } from 'pinia'
import { useShopInfo } from '/@/stores/shopInfo'

const shopInfo = useShopInfo()
const { profile } = storeToRefs(shopInfo)

const respAdGroupId = inject<Ref>('respAdGroupId')
const addedTableDataForVc2 = inject<Ref>('addedTableDataForVc2')

interface RuleForm {
  name: string
}
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
})
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      createVideo()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const activeNames = ref(['video'])
const handleChange = (val: string[]) => {
  // console.log(val)
}

const fileList = ref<UploadUserFile[]>([]) // 上传的文件列表

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  fileList.value.length = 0
  // console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length} totally`)
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
    () => true,
    () => false
  )
}

function changeFile(file) {
  // console.log('file', file)
  handleUpload(file)
}

const upLoading = ref(false)
let brandLogoCrop = {}
let respAssetId = ''
let brandEntityId = ''

async function handleUpload(file) {
  const formData = new FormData()
  formData.append('file', file.raw)
  formData.append('profile_id', profile.value.profile_id)
  formData.append('brandEntityId', brandEntityId)
  formData.append('assetType', 'VIDEO')
  formData.append('assetSubTypeList', JSON.stringify([]))
  upLoading.value = true
  try {
    const response = await uploadFile(formData)
    const fileName = response.data.file_name
    const obj = {
      profile_id: profile.value.profile_id,
      file_name: fileName,
    }
    const resp = await checkAsset(obj)
    respAssetId = resp.data.assetId
    if (resp.data.checkresult == 'success') {
      ElMessage({ message: '上传成功', type: 'success' })
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
  } finally {
    upLoading.value = false
  }
}

const createLoading = ref(false)
async function createVideo() {
  createLoading.value = true
  try {
    const obj = {
      profile_id: profile.value.profile_id,
      casins: asins.value,
      name: ruleForm.name,
      state: 'PAUSED',
      adGroupId: respAdGroupId.value,
      videoAssetIds: respAssetId,
      consentToTranslate: false,
    }
    const response = await postVideo(obj)
    if (response.data.creative_state == 'success') {
      ElMessage({ message: '创建成功', type: 'success' })
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('error:', error)
  } finally {
    createLoading.value = false
  }
}

let asins = ref([])
watch(
  addedTableDataForVc2,
  (newValue) => {
    asins.value = []
    if (Array.isArray(newValue) && newValue.length > 0) {
      newValue.forEach((item) => {
        if (item.asin && !asins.value.includes(item.asin)) {
          asins.value.push(item.asin)
        }
      })
    }
    console.log('Updated ASINs:', asins.value)
  },
  { deep: true }
)

// dialog以及选择card相关功能
const selectedId = ref(null)
const hoverId = ref(null)
const selectedCards = ref([])
const selectedImageUrl = ref('')
const centerDialogVisible = ref(false)
const cards = reactive([])
let selectedAssetId = ''

function resetSelection() {
  selectedCards.value = []
  selectedId.value = null
}

function bytesToKB(bytes) {
  return (bytes / 1024).toFixed(2) // 保留两位小数
}

async function getAssetsData() {
  const query = {
    profile_id: profile.value.profile_id,
    assetType: 'VIDEO',
    specCheckApprovedPrograms: 'SPONSORED_BRANDS_VIDEO',
  }
  const response = await getVideoAssets(query)

  cards.splice(0, cards.length)

  response.data.forEach((asset) => {
    cards.push({
      id: asset.assetId,
      title: asset.name,
      imageUrl: asset.storageLocationUrls.defaultUrl,
      width: asset.fileMetadata.resolutionWidth,
      height: asset.fileMetadata.resolutionHeight,
      size: bytesToKB(asset.fileMetadata.sizeInBytes),
    })
  })
}

function isSelected(id) {
  return selectedCards.value.some((card) => card.id === id)
}

function selectCard(item) {
  if (isSelected(item.id)) {
    selectedCards.value = selectedCards.value.filter((card) => card.id !== item.id)
  } else {
    selectedCards.value.push({
      id: item.id,
      assetId: item.id,
      title: item.title,
      imageUrl: item.imageUrl,
    })
  }
  selectedId.value = item.id
}

function handleConfirmSelection() {
  if (selectedCards.value.length > 0) {
    // 获取选中卡片的 assetId
    selectedAssetId = selectedCards.value[0].assetId
    const newFile = {
      name: selectedCards.value[0].title, // 任何可以用作文件名的字符串
      url: selectedImageUrl.value,
      // 根据需要添加更多属性
    }
    fileList.value.push(newFile)

    // 清空选中卡片
    resetSelection()
    centerDialogVisible.value = false
  }
}

function handleSelect() {
  centerDialogVisible.value = true
  getAssetsData()
}

// 创建商品创意相关
const loading = ref(false)
async function createCommodity() {
  try {
    loading.value = true
    const obj = {
      profile_id: profile.value.profile_id,
      casins: commodityCard.value[0].asin,
      name: ruleForm.name,
      state: 'ENABLED',
      adGroupId: respAdGroupId.value,
      consentToTranslate: false,
      videoAssetIds: selectedAssetId,
    }
    const response = await videoDetailCreate(obj)
    if (response.data.creative_state == 'success') {
      ElMessage({
        message: '商品创意创建成功',
        type: 'success',
      })
    } else {
      ElMessage.error('商品创意创建失败!')
    }
  } catch (error) {
    console.log('error:', error)
  } finally {
    loading.value = false
  }
}

function clickSave() {
  console.log(123, fileList.value)
  createCommodity()
  commodityCard.value.length = 0
}

// 已选择的商品
const commodityCard = ref([])

watch(
  addedTableDataForVc2,
  (newValue) => {
    commodityCard.value = newValue
  },
  { deep: true }
)
</script>

<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 0 80px;" v-loading="loading">
      <div style="font-weight: 700; padding-bottom: 18px">
        <span style="color: #306cd7; font-size: 26px">|</span>
        <span style="font-size: 18px; padding-left: 5px">创意</span>
      </div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        size="default"
        label-position="top"
        status-icon>
        <el-form-item label="广告名称" prop="name">
          <el-input v-model="ruleForm.name" style="width: 50%" />
        </el-form-item>
        <div style="display: flex; border: 1px solid #dddfe6; padding: 0 0 0 5px; margin-bottom: 20px" v-loading="createLoading">
          <div style="width: 50%; padding-left: 5px; border-right: 1px solid #dddfe6">
            <el-scrollbar height="700px">
              <el-collapse v-model="activeNames" @change="handleChange" style="border-top: none; border-bottom: none">
                <el-collapse-item name="video" style="padding: 0 10px 0 5px">
                  <template #title> <span style="color: #e47470; margin-right: 4px">*</span>视频 </template>
                  <div>
                    <div style="display: flex; align-items: center; justify-content: space-between">
                      <span style="color: #1e2128; font-size: 15px; font-weight: 450">选择视频</span>
                      <el-button type="primary" link>查看视频批准提示</el-button>
                    </div>
                    <div style="color: #666666; margin-bottom: 10px">
                      保持视频简短并紧扣主题。视频会自动播放，因此请确保前 2
                      秒极具吸引力，并且不依靠声音来传递信息。如果您在视频中使用了文字，请确保文字清晰易辨。字幕或音频必须与将展示您广告的区域相匹配。
                    </div>
                    <div class="upload-button-group">
                      <el-upload
                        v-model:file-list="fileList"
                        :on-change="changeFile"
                        v-loading="upLoading"
                        accept=".mp4, .mov"
                        action="#"
                        :limit="1"
                        :auto-upload="false"
                        :on-remove="handleRemove"
                        class="upload-demo">
                        <el-button type="primary">上传文件</el-button>

                        <!-- <template #tip>
                          <div class="el-upload__tip"><el-button type="primary" :icon="Picture"  :disabled="true" @click="handleSelect">从素材库中选择</el-button></div>
                        </template> -->
                      </el-upload>
                      <!-- <el-button type="primary" :icon="Picture" style="margin-left: -120px" :disabled="true" @click="handleSelect">从素材库中选择</el-button> -->
                    </div>
                  </div>
                </el-collapse-item>
                <div style="display: flex; align-items: center; justify-content: space-between; padding: 0 10px 0 5px">
                  <span style="color: #1e2128; font-size: 15px; font-weight: 450">视频文件要求:</span>
                  <el-button type="primary" link>了解更多</el-button>
                </div>
                <div style="padding: 0 10px 0 5px">
                  <span style="color: #1e2128; font-size: 13px; font-weight: 450">视频规格</span>
                  <div class="introduce-item">1.纵横比：16：9</div>
                  <div class="introduce-item">2.尺寸：1280 x 720 像素、1920 x 1080 像素或 3840 x 2160 像素</div>
                  <div class="introduce-item">3.文件大小：500MB 或更小</div>
                  <div class="introduce-item">4.文件格式：MP4 或 MOV</div>
                  <div class="introduce-item">5.长度：6-45 秒</div>
                  <div class="introduce-item">6.帧率：23.976、23.98、24、25、29.97 或 29.98 fps</div>
                  <div class="introduce-item">7.比特率：1 Mbps 或更高</div>
                  <div class="introduce-item">8.编解码器：H.264 或 H.265</div>
                  <div class="introduce-item">9.配置文件：主配置文件或基线配置文件</div>
                  <div class="introduce-item">10.视频流：仅为 1</div>
                </div>
                <div style="padding: 0 10px 0 5px">
                  <span style="color: #1e2128; font-size: 13px; font-weight: 450">音频规格</span>
                  <div class="introduce-item">1.语言：必须与广告投放区域匹配</div>
                  <div class="introduce-item">2.采样率：44.1 kHz 或更高</div>
                  <div class="introduce-item">3.编解码器：PCM、AAC 或 MP3</div>
                  <div class="introduce-item">4.比特率：96 kbps 或更高</div>
                  <div class="introduce-item">5.格式：立体声或单声道</div>
                  <div class="introduce-item">6.音频流：仅为 1</div>
                </div>
                <hr style="color: #eceef4; margin: 8px 10px 0 5px" />
                <el-collapse-item name="commodity" style="padding: 0 10px 0 5px">
                  <template #title> <span style="color: #e47470; margin-right: 4px">*</span>商品 </template>
                  <div v-for="item in addedTableDataForVc2" :key="item.asin">
                    <el-card shadow="hover" body-style="padding: 10px">
                      <div style="padding: 10px; display: flex; align-items: center">
                        <div style="margin-right: 8px; line-height: normal">
                          <el-image class="img-box" :src="item.image_link" />
                        </div>
                        <div style="position: relative">
                          <el-tooltip class="box-item" effect="dark" :content="item.title" placement="top">
                            <div class="double-line">{{ item.title }}</div>
                          </el-tooltip>
                          <span>
                            <span style="color: #6d7784">ASIN: </span>
                            <span class="data-color" style="margin-right: 8px">{{ item.asin }}</span>
                          </span>
                        </div>
                      </div>
                    </el-card>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </el-scrollbar>
          </div>
          <div style="width: 50%; padding: 0 10px; position: relative">
            <el-button
              type="primary"
              plain
              @click="submitForm(ruleFormRef)"
              :disabled="!commodityCard.length && addedTableDataForVc2"
              style="position: absolute; top: 92%; left: 46%"
              >保存</el-button
            >
          </div>
        </div>
      </el-form>
    </el-card>
    <el-dialog v-model="centerDialogVisible" title="从素材库中选择" width="65%">
      <el-input :prefix-icon="Search"></el-input>
      <div class="grid-container">
        <div
          class="grid-item"
          v-for="item in cards"
          :key="item.id"
          @click="selectCard(item)"
          :class="{ selected: isSelected(item.id), hover: hoverId === item.id }"
          @mouseover="hoverId = item.id"
          @mouseleave="hoverId = null">
          <el-card :body-style="{ padding: '0px' }">
            <video class="image" :src="item.imageUrl" controls preload="none" @click.stop></video>
            <div style="padding: 10px">
              <span>
                <el-tooltip placement="top" :content="item.title">
                  {{ item.title }}
                </el-tooltip>
              </span>
              <div class="bottom">
                <div class="bottom-item">{{ item.size }}KB</div>
                <div class="bottom-item">{{ item.width }} * {{ item.height }}</div>
                <div class="bottom-item">背景视频</div>
              </div>
            </div>
          </el-card>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmSelection">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.customize-container {
  margin-top: 10px;
}
.upload-button-group {
  display: flex;
}
.introduce-item {
  line-height: 17px;
  font-size: 12px;
  color: #88909b;
}
.grid-container {
  flex-wrap: wrap;
  display: flex;
  width: 100%;
  justify-content: left;
}
.grid-item {
  transition: outline, background-color 0.3s;
  box-sizing: border-box;
  border: 1px solid #ffffff00;
  cursor: pointer;
  width: calc(25% - 10px);
  margin: 10px 5px;
}
.grid-item span {
  display: block; /* 或者 inline-block */
  white-space: nowrap; /* 保持文本在一行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  max-width: 100%; /* 限制最大宽度 */
  font-weight: 600;
  line-height: 22px;
}
.grid-item.hover,
.grid-item.selected {
  border: 1px solid #306cd8;
  border-radius: 4px;
}
.grid-item.selected > :first-child {
  background-color: #f5f7fe;
}
.image {
  width: 100%;
  height: 146.49px;
  padding: 10px;
}
.image > :first-child {
  border-radius: 10px;
}
.bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}
.bottom-item {
  background-color: #f5f7fe;
  border-radius: 4px;
  padding: 0 3px;
}
.img-box {
  width: 60px;
  height: 60px;
  border: 1px solid rgb(194, 199, 207);
  border-radius: 4px;
}
.double-line {
  color: #1e2128;
  font-weight: 500;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
