<!-- @format -->

<script lang="ts" setup>
import { useUserStore } from '@/stores/modules/user'
import { ossUploadApi } from '@/api/model/common'
import { addShopCartApi } from '~/api/model/goods'

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
})
const emit = defineEmits(['update:data'])

const { openLoginModal } = useLoginModal()
const temporaryData = ref()
const input = ref(null)
const loading = ref(false)
const price = ref(0)
const fileArrList = ref<any>([])
const params = ref<any>({
  file: '',
  mid: '',
  quantity: '',
  remark: '',
})

const userStore = useUserStore()
const { isLogin } = storeToRefs(userStore)
const visible = defineModel('visible', { type: Boolean, required: true })
function handleClose() {
  console.log('close')
}

watch(
  () => props.data,
  (data: any) => {
    temporaryData.value = JSON.parse(JSON.stringify(data))
    params.value.quantity = +data.moq
    params.value.mid = data.id
    price.value = +data.sellPrice
  },
  {
    immediate: true,
    deep: true,
  },
)
const totalPrice = computed(() => {
  return (params.value.quantity * price.value).toFixed(2)
})
function changeQuantity(currentValue: any) {
  params.value.quantity = currentValue
}
function uploadData() {
  input.value?.click()
}
function inputChange(e: any) {
  const fileList = e.target.files
  // fileList 转化为正式数组
  const fileArr = Array.from(fileList)
  fileArr.forEach(async (file: any) => {
    const resourceUrl = await getResource(file)
    fileArrList.value.push(resourceUrl)
  })
}
async function getResource(file: any) {
  try {
    if (file.size > 1024 * 1024 * 10)
      return ElMessage.error('Image size cannot exceed 10M')
    return await ossUploadApi(file)
  }
  catch (error) {
    ElMessage.error('send failed')
  }
}
function getFileTitle(file: string) {
  const fileArr = file.split('/')
  return fileArr[fileArr.length - 1]
}
function del(i: number) {
  fileArrList.value = fileArrList.value.filter((item, index) => index !== i)
}
async function addShopCart() {
  try {
    loading.value = true
    const { status, isFirstLogin }: any = await openLoginModal()
    if (status) {
      params.value.file = fileArrList.value.join(',')
      await addShopCartApi(params.value)
      ElMessage({
        message: 'Add to cart successfully',
        type: 'success',
        plain: true,
      })
      loading.value = false
      visible.value = false
      if (isFirstLogin)
        emit('update:data')
    }
  }
  catch (error) {
    loading.value = false
    console.log(error)
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <el-dialog
    v-model="visible"
    :append-to-body="true"
    width="800"
    modal-class="custom-select-modal"
    @close="handleClose"
  >
    <template #header>
      <div
        class="px-40px py-25px bg-#F5F5F5 b-rd-lt-6px b-rd-rt-6px text-18px fw-700 text-#333"
      >
        Select quantity
      </div>
    </template>
    <div class="py-20px px-40px pb-0">
      <div class="r-rd-8px bg-#F9F9F9 p-24px flex">
        <img
          :src="data?.goodsImgOrVideoList[0]"
          alt=""
          srcset=""
          class="w-120px h-120px b-solid b-1px b-#e0e0e0 mr-24px"
        >
        <div>
          <div class="mb-34px custom-title-font !text-20px !fw-700">
            {{ data.merchandiseEnglishName }}
          </div>
          <div class="text-#666">
            MOQ: {{ data.moq }} {{ data.unitCode_dictText }}
          </div>
        </div>
      </div>
      <div class="flex justify-end items-center mt-24px mb-20px">
        <!-- <div class="fw-500 mr-20px">
          $ {{ price }}
        </div> -->
        <el-input-number
          :disabled="!isLogin"
          :model-value="params.quantity"
          class="!w-150px custom-input"
          :step="1"
          :min="data.moq"
          @change="changeQuantity"
        />
      </div>
      <div class="mb-24px text-20px fw-700">
        Remark
      </div>
      <div>
        <el-input
          v-model="params.remark"
          style="width: 100%"
          :rows="5"
          type="textarea"
          placeholder="Please input"
        />
        <div class="my-20px py-8px px-20px b-rd-4px cursor-pointer bg-#f0f6ff inline-block" @click="uploadData">
          <svgo-enclosure class="!w-32px !h-32px text-#0068FF" />
          <input
            ref="input"
            multiple="true"
            type="file"
            class="hidden"
            @change="inputChange"
          >
        </div>
        <div>
          <div
            v-for="(items, index) in fileArrList"
            :key="index"
            class="py-14px px-16px bg-#F7F8FA flex items-center justify-between mb-16px b-solid b-1px b-#E0E0E0 b-rd-4px"
          >
            <div class="flex items-center">
              <svgo-file
                class="!w-20px cursor-pointer !h-20px text-#333 mr-16px"
              />
              附件{{ index }}：
              <a :href="items"> {{ getFileTitle(items) }}</a>
            </div>
            <img src="@/assets/images/file_delete.png" class="!w-20px cursor-pointer !h-20px" alt="" srcset="" @click="del(index)">
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div>
        <!-- <div class="mb-8px">
          Subtotal
        </div>
        <div class="text-20px fw-700 text-#333">
          $ {{ totalPrice }}
        </div> -->
      </div>
      <el-button
        plain
        :loading="loading"
        class="!bg-#C58C46 !text-#fff !w-240px !h-48px !text-16px !b-rd-6px"
        @click="addShopCart"
      >
        <!-- Add to Cart (${{ quantity * price ? (quantity * price).toFixed(2) : 0 }}) -->
        Add to Cart
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="less">
.custom-select-modal {
  .el-dialog {
    padding: unset !important;
    .el-dialog__header {
      padding: 0 !important;
      .el-dialog__headerbtn {
        right: 10px;
        top: 10px;
      }
    }
    .el-dialog__footer {
      padding-top: 25px !important;
      padding-bottom: 24px !important;
      padding-left: 40px !important;
      padding-right: 40px !important;
      border-top: 1px solid #E0E0E0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      text-align: left;
    }
  }
}
</style>
