<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 0 80px;">
      <div class="custom-card-title">
        <span class="custom-card-icon">|</span>
        <span class="custom-card-Text">创意</span>
      </div>
      <div class="main-container" v-loading="createLoading">
        <div class="left-container">
          <div style="display: flex; justify-content: space-between;">
            <p class="left-part-title">请选择您想要自定义商品广告的方式</p>
          </div>
          
          <el-scrollbar height="755px">
            <div class="demo-collapse">
              <el-collapse v-model="activeNames" style="border: none">
                <el-collapse-item title="徽标" name="logo" v-loading="logoLoading">
                  <div style="display: flex; margin-bottom: 5px">
                    <p style="font-weight: 700; color: #1d2129; margin-right: 8px">品牌标识</p>
                    <el-switch v-model="isOpenLogo" size="small" />
                  </div>
                  <el-upload
                    v-model:file-list="logoFileList"
                    :on-change="changeLogo"
                    :on-remove="removeLogo"
                    action="#"
                    accept=".png, .jpg"
                    :limit="1"
                    list-type="picture-card"
                    :auto-upload="false">
                    <el-icon><Plus /></el-icon>
                    <template #file="{ file }">
                      <div>
                        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                        <span class="el-upload-list__item-actions">
                          <span class="el-upload-list__item-preview" @click="logoPreview(file)">
                            <el-icon><zoom-in /></el-icon>
                          </span>
                          <span v-if="!disabled" class="el-upload-list__item-delete" @click="removeLogo()">
                            <el-icon><Delete /></el-icon>
                          </span>
                        </span>
                      </div>
                    </template>
                    <template #tip>
                      <div style="margin-top: 10px">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                          <span style="line-height: 17px; font-weight: 600; color: #1e2128">徽标要求</span>
                          <!-- <el-button type="primary" :icon="Picture" @click="openDialog">从素材库中选择</el-button> -->
                        </div>
                        <div class="introduce-item">1、图片大小: 至少600x100 像素</div>
                        <div class="introduce-item">2、文件大小: 小于1MB</div>
                        <div style="display: flex; justify-content: space-between">
                          <span class="introduce-item">3、文件格式: PNG 或 JPG</span>
                          <span style="margin-left: 25px; position: relative">
                            <el-icon size="14" style="position: absolute; left: -15px; top: 6px"><Link /></el-icon>
                            <el-link
                              type="primary"
                              :underline="false"
                              href="https://advertising.amazon.com/resources/ad-policy/sponsored-ads-policies#brandlogo"
                              target="_blank"
                              >查看要求
                            </el-link>
                          </span>
                        </div>
                      </div>
                    </template>
                  </el-upload>
                  <!-- 预览弹窗 -->
                  <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogLogoUrl" alt="Preview Image" />
                  </el-dialog>
                  <CropperLogo />
                </el-collapse-item>
                <el-collapse-item title="标题" name="title">
                  <div style="display: flex">
                    <el-switch v-model="isOpenTitle" style="margin-right: 10px" />
                    <el-input v-model="titleInp" maxlength="50" show-word-limit placeholder="Please input" type="text" />
                  </div>
                  <div style="display: flex; align-items: center; flex-direction: row-reverse">
                    <el-link
                      type="primary"
                      href="https://advertising.amazon.com/resources/ad-policy/creative-acceptance#editorialguidelines"
                      target="_blank"
                      :underline="false">
                      查看政策
                    </el-link>
                    <el-icon size="14" style="margin-right: 1px"><Link /></el-icon>
                  </div>
                </el-collapse-item>
                <el-collapse-item title="图片" name="image" v-loading="imgLoading">
                  <div>
                    <div style="display: flex; margin-bottom: 5px">
                      <p style="font-weight: 700; color: #1d2129; margin-right: 8px">添加图片</p>
                      <el-switch v-model="isOpenPicture" size="small" />
                    </div>
                    <el-upload
                      v-model:file-list="imgFileList"
                      :on-change="changeImg"
                      :on-remove="removeImg"
                      action="#"
                      accept=".png, .jpeg, .gif"
                      :limit="1"
                      list-type="picture-card"
                      :auto-upload="false"
                      style="margin-bottom: 8px;">
                      <el-icon><Plus /></el-icon>
                      <template #file="{ file }">
                        <div>
                          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                          <span class="el-upload-list__item-actions">
                            <span class="el-upload-list__item-preview" @click="imgPreview(file)">
                              <el-icon><zoom-in /></el-icon>
                            </span>
                            <span v-if="!disabled" class="el-upload-list__item-delete" @click="removeImg()">
                              <el-icon><Delete /></el-icon>
                            </span>
                          </span>
                        </div>
                      </template>
                      <template #tip>
                        <div style="margin-top: 10px">
                          <div style="display: flex; align-items: center; justify-content: space-between">
                            <span style="line-height: 17px; font-weight: 600; color: #1e2128">徽标要求</span>
                          </div>
                          <div class="introduce-item">1、图片大小: 至少1200x628 像素</div>
                          <div class="introduce-item">2、文件大小: 小于5MB</div>
                          <div class="introduce-item">3、文件格式: PNG, JPEG 或GIF</div>
                          <div class="introduce-item">4、没有在图片上添加文字, 图形或徽标</div>
                        </div>
                      </template>
                    </el-upload>
                    <el-dialog v-model="imgDialogVisible">
                      <img w-full :src="dialogImgUrl" alt="Preview Image" />
                    </el-dialog>
                    <CropperImg />
                  </div>
                  <!-- 628x628图片上传 -->
                  <el-divider border-style="dashed" />
                  <div style="display: flex; margin-bottom: 5px">
                    <p style="font-weight: 700; color: #1d2129; margin-right: 8px">628x628</p>
                  </div>
                  <CropperImg628 />
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-scrollbar>
        </div>
        <div class="right-container">
          <div class="preview-title-line">
            <p class="right-part-title">广告预览</p>
            <el-select v-model="previewSelect"></el-select>
          </div>
          <el-button style="position: absolute; bottom: 5px; right: 50%;" type="primary" :icon="Check" circle @click="createCreativity" />
        </div>
      </div>
      
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { Delete, Plus, ZoomIn, Check } from '@element-plus/icons-vue'
import type { UploadFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { storeToRefs } from 'pinia'
import { Ref, inject, onMounted, onBeforeUnmount, ref } from 'vue'
import { checkAsset, postCreative, uploadFile } from '../api/index'
import { useShopInfo } from '/@/stores/shopInfo'
import emitter from '/@/utils/emitter'
import CropperLogo from '../component/CropperLogo.vue'
import CropperImg from '../component/CropperImg.vue'
import CropperImg628 from './CropperImg-628.vue'


const respAdGroupId = inject<Ref>('respAdGroupId')
const shopInfo = useShopInfo()
const { profile } = storeToRefs(shopInfo)

// 折叠面板相关
const activeNames = ref([''])

// logo相关
const logoFileList = ref([])
const logoLoading = ref(false)
const disabled = ref(false)
const dialogVisible = ref(false)
const dialogLogoUrl = ref('')
const centerDialogVisible = ref(false)
const logoImg = ref('')
let logoDimension = {
  left: 0,
  top: 0,
  width: 0,
  height: 0,
}

emitter.on('send-logo-leftTop', (value: any) => {
  logoDimension.left = value.left
  logoDimension.top = value.top
  logoDimension.width = value.width
  logoDimension.height = value.height
})

function changeLogo(file: UploadFile) {
  emitter.emit('logo-src', file.url)
  logoImg.value = file.url
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (imgInfo: any) => {
    const img = new Image()
    img.src = imgInfo.target.result
    img.onload = () => {
      emitter.emit('logo-data', img)
      if (img.width >= 600 && img.height >= 100) {
        handleUpload(file)
      } else {
        logoFileList.value = []
        ElMessage.error('不符合尺寸要求')
      }
    }
  }
}

function removeLogo() {
  logoFileList.value = []
}

function logoPreview(file: UploadFile) {
  dialogLogoUrl.value = file.url!
  dialogVisible.value = true
}

// 文件上传相关
const brandEntityId = ref('')
let brandLogoAssetID = ''
let brandLogoAssetVersion = ''
const isOpenLogo = ref(false)

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

function openDialog() {
  centerDialogVisible.value = true
  // getAssetsData()
}

// 标题相关
const titleInp = ref('')
const isOpenTitle = ref(false)

// 图片相关
const imgFileList = ref([])
const imgLoading = ref(false)
const isOpenPicture = ref(false)
const imgDialogVisible = ref(false)
const dialogImgUrl = ref('')
let pictureAssetVersion2 = ''
let pictureAssetID2 = ''
let imgDimension = {
  left: 0,
  top: 0,
  width: 0,
  height: 0,
}
let imgDimension628 = {
  left: 0,
  top: 0,
  width: 0,
  height: 0,
}

emitter.on('send-img-leftTop', (value: any) => {  // 获取图片的坐标和尺寸
  imgDimension.left = value.left
  imgDimension.top = value.top
  imgDimension.width = value.width
  imgDimension.height = value.height
})

emitter.on('send-img628-leftTop', (value: any) => {
  imgDimension628.left = value.left
  imgDimension628.top = value.top
  imgDimension628.width = value.width
  imgDimension628.height = value.height
})

function changeImg(file: UploadFile) {
  emitter.emit('img-src', file.url)
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = (imgInfo: any) => {
    const img = new Image()
    img.src = imgInfo.target.result
    img.onload = () => {
      emitter.emit('img-data', img)
      if (img.width >= 1200 && img.height >= 628) {
        handleUploadPicture2(file)
      } else {
        imgFileList.value = []
        ElMessage.error('不符合尺寸要求')
      }
    }
  }
}

function removeImg() {
  imgFileList.value = []
}

function imgPreview(file: UploadFile) {
  dialogImgUrl.value = file.url!
  imgDialogVisible.value = true
}

async function handleUploadPicture2(file: UploadFile) {
  const formData = new FormData()
  formData.append('file', file.raw)
  formData.append('profile_id', profile.value.profile_id)
  formData.append('brandEntityId', brandEntityId.value)
  formData.append('assetType', 'IMAGE')
  formData.append('assetSubTypeList', JSON.stringify(['LIFESTYLE_IMAGE', 'OTHER_IMAGE']))
  imgLoading.value = true
  try {
    const response = await uploadFile(formData)
    pictureAssetVersion2 = response.data.third.versionId
    const fileName = response.data.file_name
    const obj = {
      profile_id: profile.value.profile_id,
      file_name: fileName,
    }
    const resp = await checkAsset(obj)
    pictureAssetID2 = resp.data.assetId

    if (resp.data.checkresult == 'success') {
      ElMessage({ message: '上传成功', type: 'success' })
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
  } finally {
    imgLoading.value = false
  }
}

// 创建创意相关
const createLoading = ref(false)

async function createCreativity() {
  createLoading.value = true
  const obj = {
    profile_id: profile.value.profile_id,
    adGroupId: respAdGroupId.value,
    properties_logo: isOpenLogo.value,
    properties_head: isOpenTitle.value,
    properties_custom: isOpenPicture.value,
    headline: titleInp.value,
    brandLogo_assetId: brandLogoAssetID,
    brandLogo_assetVersion: brandLogoAssetVersion,
    brandLogo_croppingCoordinates: logoDimension,
    custom_assetId: pictureAssetID2,
    custom_assetVersion: pictureAssetVersion2,
    rectCustomImage_croppingCoordinates: imgDimension,
    squareCustomImage_croppingCoordinates: imgDimension628,
  }
  try {
    const response = await postCreative(obj)
    if (response.data.result[0].code == 'SUCCESS') {
      ElMessage({ message: '创建成功', type: 'success' })
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('error:', error)
  } finally {
    createLoading.value = false
  }
}

const previewSelect = ref('')

onMounted(() => {
  emitter.on('send-brandEntityId', (value: any) => {
    brandEntityId.value = value.brandEntityId[0].brandEntityId
  })
})

onBeforeUnmount(() => {
  emitter.all.clear()
})
</script>

<style scoped>
.customize-container {
  margin-top: 10px;
}
.custom-card-title {
  font-weight: 700;
  padding-bottom: 18px;
}
.custom-card-Text {
  font-size: 18px;
  padding-left: 5px;
}
.custom-card-icon {
  color: #306cd7;
  font-size: 26px;
}
.main-container {
  display: flex;
  border: 1px solid #e5e7eb;
  height: 800px;
  margin-bottom: 20px;
  border-radius: 6px;
}
.left-container {
  width: 50%;
  padding: 10px;
  border-right: 1px solid #e5e7eb;
}
.left-part-title {
  color: #4e5969;
  padding-bottom: 4px;
  height: 32px;
  font-weight: 700;
  line-height: 32px;
}
.preview-title-line {
  display: flex;
  align-items: center;
}
.right-container {
  position: relative;
  width: 50%;
  padding: 10px;
  border-right: 1px solid #e5e7eb;
}
.right-part-title {
  color: #4e5969;
  padding-bottom: 4px;
  margin-right: 8px;
  height: 32px;
  font-weight: 700;
  line-height: 32px;
}
.introduce-item {
  line-height: 17px;
  font-size: 12px;
  color: #88909b;
}
::v-deep(.el-collapse > .el-collapse-item:last-child .el-collapse-item__header) { /* 移除collapse底部的线 */
  border-bottom: none;
}
::v-deep(.el-collapse > .el-collapse-item:last-child .el-collapse-item__wrap) {
  border-bottom: none;
}

</style>
