<script setup lang="ts">
import { reactive, ref, inject, Ref, watch, onMounted, onUnmounted } from 'vue'
import type { FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import { checkAsset, uploadFile, postProductset } from '../api/index'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
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 setBrandName = inject<Ref>('setBrandName')
const addedTableDataForVc2 = inject<Ref>('addedTableDataForVc2')

interface RuleForm {
  name: string
  brandName: string
  title: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  name: '',
  brandName: '',
  title: '',
})

const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入广告名称', trigger: 'blur' }],
  brandName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      createCreativity()
    } else {
      console.log('error submit!', fields)
    }
  })
}

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

const fileList = ref<UploadUserFile[]>([])

const customFileList = ref<UploadUserFile[]>([])

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

const handleCustomRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
  fileList.value = []
}

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
  )
}

const upLoading = ref(false)
let brandLogoAssetID = ''
let brandLogoCrop = {}
let createLoading = ref(false)
const brandEntityId = inject<Ref>('brandEntityId')

function changeFile(file) {
  handleUpload(file)
}

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.value)
  formData.append('assetType', 'IMAGE')
  formData.append('assetSubTypeList', JSON.stringify(['LOGO']))
  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)
    brandLogoAssetID = resp.data.assetId
    const { width, height } = resp.data.fileMetadata
    brandLogoCrop = {
      width,
      height,
      top: 0,
      left: 0,
    }
    if (resp.data.checkresult == 'success') {
      ElMessage({ message: '上传成功', type: 'success' })
    } else {
      ElMessage.error('上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
  } finally {
    upLoading.value = false
  }
}

// 自定义图片上传
const upCustomLoading = ref(false)
const lasins = ref('')
let customImageAssetId = ''
let customImageCrop = {}


function changeCustomFile(file) {
  handleCustomUpload(file)
}

async function handleCustomUpload(file) {
  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']))
  upCustomLoading.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)
    customImageAssetId = resp.data.assetId
    const { width, height } = resp.data.fileMetadata
    brandLogoCrop = {
      width,
      height,
      top: 0,
      left: 0,
    }

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

// TODO: url对应的是Home 暂时写死
async function createCreativity() {
  createLoading.value = true
  try {
    const obj = {
      profile_id: profile.value.profile_id,
      casins: lasins.value,
      lasins: lasins.value,
      url: 'https://www.amazon.com/stores/page/1D1DD2FD-CF54-4FE5-B1A0-9E01F12F8144',
      name: ruleForm.name,
      state: 'PAUSED',
      adGroupId: respAdGroupId.value,
      brandName: setBrandName.value,
      brandLogoCrop: brandLogoCrop,
      brandLogoAssetID: brandLogoAssetID,
      customImageCrop: customImageCrop,
      customImageAssetId: customImageAssetId,
      headline: ruleForm.title,
    }
    const response = await postProductset(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 }
)

const commodityCard = ref([])

watch(
  commodityCard,
  (newValue: any) => {
    lasins.value = newValue.map(item => item.asin)
  },
  { deep: true }
)

onMounted(() => {
  emitter.on('addedTableData', (data: any) => {
    commodityCard.value = data
  })
})

// 接收数据端在组件卸载时解绑事件
onUnmounted(() => {
  emitter.off('addedTableData')
})

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

<template>
  <div class="customize-container">
    <el-card body-style="padding: 20px 80px 0 80px;">
      <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; padding-right: 10px;">
                <el-collapse-item name="1">
                  <template #title> <span style="color: #e47470; margin-right: 4px">*</span>品牌名称和徽标</template>
                  <el-form-item prop="brandName">
                    <el-input v-model="ruleForm.brandName" placeholder="请输入品牌名称" style="padding: 0 10px 5px 0"></el-input>
                  </el-form-item>
                  <el-upload
                    drag
                    v-model:file-list="fileList"
                    :on-change="changeFile"
                    v-loading="upLoading"
                    action="#"
                    accept=".png, .jpg"
                    :auto-upload="false"
                    :on-remove="handleRemove"
                    style="padding-right: 10px">
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">Drop file here or <em>click to upload</em></div>
                    <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">从素材库中选择</el-button>
                        </div>
                        <div class="introduce-item">1、图片大小: 400x400 像素或更大</div>
                        <div class="introduce-item">2、文件大小: 1MB 或更小</div>
                        <div class="introduce-item">3、文件格式: PNG 或 JPG</div>
                        <div class="introduce-item">
                          4、内容: 徽标必须填满图片或置于白色或透明背景上详细了解我们的徽标要求
                          <span style="margin-left: 25px; position: relative">
                            <el-icon size="14" style="position: absolute; left: -14px; top: 1px"><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-collapse-item>
                <el-collapse-item name="2">
                  <template #title>自定义图片(可选)</template>
                  <el-upload
                    class="avatar-uploader"
                    v-model:file-list="customFileList"
                    :on-change="changeCustomFile"
                    v-loading="upCustomLoading"
                    action="#"
                    accept=".png, .jpg"
                    :auto-upload="false"
                    :on-remove="handleRemove"
                    style="padding-right: 10px">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                    <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">从素材库中选择</el-button>
                        </div>
                        <div class="introduce-item">1、图片大小: 1200 x 628 像素或更大</div>
                        <div class="introduce-item">2、文件大小: 5MB 或更小</div>
                        <div class="introduce-item">3、文件格式: PNG 或 JPG</div>
                        <div class="introduce-item">4、内容: 图片中未添加文本、图形或徽标</div>
                      </div>
                    </template>
                  </el-upload>
                </el-collapse-item>
                <el-collapse-item name="3">
                  <template #title> <span style="color: #e47470; margin-right: 4px">*</span>商品</template>
                  <div v-for="item in commodityCard" :key="item.asin" style="padding-bottom: 5px;">
                    <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="single-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-item name="4">
                  <template #title> <span style="color: #e47470; margin-right: 4px">*</span>标题</template>
                  <el-form-item prop="title">
                    <el-input v-model="ruleForm.title" maxlength="50" placeholder="请输入标题" show-word-limit style="padding: 0 10px 0 0"></el-input>
                  </el-form-item>
                </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="!fileList.length"
              style="position: absolute; top: 92%; left: 46%">
              保存
            </el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.customize-container {
  margin-top: 10px;
}
.upload-button-group {
  display: flex;
}
.introduce-item {
  line-height: 17px;
  font-size: 12px;
  color: #88909b;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

::v-deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}
::v-deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
::v-deep(.avatar-uploader .el-upload.el-upload--text) {
  width: 100%;
}
.img-box {
  width: 60px;
  height: 60px;
  margin-top: 5px;
  border: 1px solid rgb(194, 199, 207);
  border-radius: 4px;
}
.single-line {
  color: rgb(30, 33, 41);
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  white-space: pre-wrap;
  word-break: break-word;
}
.data-color {
  color: rgb(30, 33, 41);
}
</style>
