<template>
  <div>
    <h1>Сделка</h1>
    <div><a href="#" @click.prevent="createDeal(1481170)">Создать новую сделку</a></div>
    <div><a href="#" @click.prevent="editDeal(1481170, 46)">Открыть тестовую сделку</a></div>
  </div>
  <DynamicDialog />
</template>


<script setup>
import { ref, onMounted } from 'vue'
import DealModal from './components/deal/DealModal.vue'
import DynamicDialog from 'primevue/dynamicdialog'
import {useDialog} from "primevue/usedialog";

const isOpen = ref(false)
const dealId = ref(null)
const newDealReqId = ref(null)
const dialog = useDialog()

const refreshRequisitions = () => {
  if (window.requisitions && typeof window.requisitions.getList === 'function') {
    window.requisitions.getList()
  }
}

const createDeal = (newDealReqId) => {
  console.log('[createDeal] Открываем DealModal через DynamicDialog', newDealReqId)

  dialog.open(DealModal, {
    props: {
      header: 'Создание сделки',
      style: { width: '85vw' },
      modal: true
    },
    data: {
      newDealReqId: newDealReqId
    },
    onClose: (opt) => {
      console.log('[DynamicDialog] Закрыто с данными:', opt?.data)
      refreshRequisitions()
    }
  })
}

const editDeal = (newDealReqId, dealId) => {
  console.log('[editDeal] Открываем DealModal через DynamicDialog', dealId)

  $('#client-history__bg').hide(10);
  $('#client_history').hide(10);
  $('#object-history__bg').hide(10);
  $('#object-history').hide(10);
  $('body').removeClass('lock');

  dialog.open(DealModal, {
    props: {
      header: 'Редактирование сделки',
      style: { width: '85vw' },
      modal: true
    },
    data: {
      newDealReqId: newDealReqId,
      deal_id: dealId
    },
    onClose: (opt) => {
      console.log('[DynamicDialog] Закрыто с данными:', opt?.data)
      refreshRequisitions()
    }
  })
}

// const editDeal = (id) => {
//   isOpen.value = true
//   dealId.value = id
//   newDealReqId.value = null
// }

const backToStep = () => {
  isOpen.value = false
}

onMounted(() => {
  window.createDeal = createDeal
  window.createDealReady = true
  window.editDeal = editDeal
  window.backToStep = backToStep

  console.log('✅ window.createDeal доступна')
})
</script>
