import { ref } from "vue"

import { ElMessage } from "element-plus"

export function useOseCardEditPage({ data, props, query, router, store, beforeSave }) {
  const previewButtonDisabled = ref(true)
  const pageLoading = ref(false)

  const initializePage = async () => {
    for (const key in props) {
      data[key] = props[key]
    }

    if (store.state.ose_card_store.timer_id) {
      clearInterval(store.state.ose_card_store.timer_id)
    }

    if (query.id) {
      for (const key in data) {
        data[key] = store.state.ose_card_store.edit_card_data[key]
      }
    }

    data.corporate_customer = store.state.user.current_corporate_customer

    if (query.mode === "edit") {
      previewButtonDisabled.value = false
    }

    if (store.state.ose_card_store.images.length === 0) {
      await store.dispatch("ose_card_store/getImages")
    }
  }

  const goBack = () => {
    router.go(-1)
  }

  const saveRecord = async () => {
    pageLoading.value = true

    const params = {
      mode: query.mode,
      id: query.id,
      item: data,
    }

    if (!data.card_name || !data.landing_page || !data.card_code || !data.start_date || !data.end_date) {
      ElMessage({
        showClose: true,
        message: "【圖卡名稱、LandingPage、圖卡代碼、開始/結束時間】不得為空。",
        type: "error",
      })
      pageLoading.value = false
      return
    }

    const filterResult = await store.dispatch("ose_card_store/saveCardFilter", params)

    if (filterResult.length > 0) {
      ElMessage({
        showClose: true,
        message: "該圖卡有重複到【LandingPage、圖卡代碼、開始/結束時間】，請再次檢查。",
        type: "warning",
      })
      pageLoading.value = false
      return
    }

    if (beforeSave) {
      beforeSave()
    }

    await store.dispatch("ose_card_store/saveCard", params)

    ElMessage({
      showClose: true,
      message: "圖卡保存完成！",
      type: "success",
    })

    if (query.mode !== "edit") {
      router.go(-1)
    }

    pageLoading.value = false
  }

  const applyColorChange = (target, color) => {
    if (typeof target === "string") {
      data[target] = color
      return
    }

    for (const key of target) {
      data[key] = color
    }
  }

  return {
    pageLoading,
    previewButtonDisabled,
    initializePage,
    goBack,
    saveRecord,
    applyColorChange,
  }
}
