<script setup lang="ts">
import { getIntegratedApproval } from '/src/service/integratedApproval'
import type { VFlexTableWrapperSortFunction, VFlexTableWrapperFilterFunction } from '/src/components/app-vuero/ComVFlexTableWrapper.vue'
import { users } from '/src/data/layouts/card-grid-v1'
import PriceDetail from "/@src/pages/app/priceDetail.vue";
import {conveterNo, updateApprovalStatus} from "/@src/service/approvalApi.ts";
import {formatDatefromString} from "/@src/utils/common/comfunc.ts";
import {getPriceList} from "/@src/service/priceApi.ts";
import {getContractList} from "/@src/service/contractApi.ts";


onBeforeMount(async () => {
  await getIntegratedPaymentList()
})
const isModalOpen = ref(false)
const selectedRow = ref<any>(null)
const prcsNo = ref<string>('')
const router = useRouter()
const totalItems = ref(0)        // 전체 아이템 수
const currentPage = ref<number>(1)       // 현재 페이지
const itemsPerPage = 8
const totalPages = ref(1)

async function getApprovalListData(){
  const today = new Date()
  searchParamsList.regSdt = new Date().setDate(today.getDate() - 30)
  searchParamsList.regEdt = new Date().setDate(today.getDate())

  const priceBase = {
    params:{
      regSdt: formatDatefromString(searchParamsList.regSdt),
      regEdt: formatDatefromString(searchParamsList.regEdt),
      page: 1,
      row: itemsPerPage
    }
  }
  const result = await getPriceList(priceBase)
  params.priceData = result.content
  //페이지 관련 값 설정
  totalItems.value = result.totalElements
  totalPages.value = result.totalPages
}

const searchApprovalDoc = async (item) => {
  const searchParams = {
    params: {
      title : searchParamsList.title, //제목
      regSdt: formatDatefromString(searchParamsList.regSdt),//등록시작일
      regEdt: formatDatefromString(searchParamsList.regEdt),//등록종료일
      page: item,//페이지
      row: itemsPerPage //아이템갯수
    }
  }
  const result = await getContractList(searchParams)
  params.priceData = result.content
  totalItems.value = result.totalElements
}

const masks = ref({
  modelValue: 'YYYY-MM-DD',
})
const notyf = useNotyf()

const params = reactive({
  title: '',
  priceData: [],
  regSdt:'',
  regEdt:'',
  flexColumn: [
    { key: 'process', label: '구분', cellClass: 'approvalColumn1', align: 'center' },
    { key: 'apprNo', label: '결재번호', cellClass: 'approvalColumn1', align: 'center' },
    { key: 'title', label: '제목', cellClass: 'approvalColumn6', align: 'start' },
    { key: 'name', label: '작성자', cellClass: 'approvalColumn1', align: 'center' },
    {
      key: 'regDt',
      label: '등록일',
      cellClass: 'approvalColumn1',
      format: formatRegDt,
    },
  ],
  approvalParams: [],
  rowData: [],
})

function formatRegDt(value) {
  return value ? value.substring(0, 16) : ''
}

async function getIntegratedPaymentList() {
  const approvalParams = {
    title: '',
    page: '1',
    row: '10',
    sabun: '17131303', // 김진형 17131303, 손원창 17131304
  }
  const result = await getIntegratedApproval(approvalParams)
  params.approvalParams = result.content.map(item => ({
    ...item,
    process: gubunMap[item.gubun] || '',
  }))
  //페이지 관련 값 설정
  totalItems.value = result.totalElements
  totalPages.value = result.totalPages
}

async function updateIntegratedPaymentApprovalFunc() {
  const approvalUpdateParams = {
    apprNo: params.rowData.apprNo,
    apprOrd: params.rowData.apprOrd,
    sabun: params.rowData.sabun,
    apprStatCd: '0200', // 결재 상태변경 (결재승인 0200 결재회수 0300 결재반려 0400)
    reason: '',
  }
  const result = await updateApprovalStatus(approvalUpdateParams)
  notyf.primary("결재승인완료")
  window.location.reload()
}

async function updateIntegratedPaymentRejectionFunc() {
  const approvalUpdateParams = {
    apprNo: params.rowData.apprNo,
    apprOrd: params.rowData.apprOrd,
    sabun: params.rowData.sabun,
    apprStatCd: '0400', // 결재 상태변경 (결재승인 0200 결재회수 0300 결재반려 0400)
    reason: '',
  }
  const result = await updateApprovalStatus(approvalUpdateParams)
  notyf.primary("결재반려완료")
  window.location.reload()
}

const gubunMap = {
  SAP: '전표생성',
  SVCM: '가격조사',
}

const searchApproval = async () => {
  const searchParams = {
    params: {
      title: params.title,
      page: '1',
      row: '10',
    },
  }
  const result = await getIntegratedApproval(searchParams)
  params.approvalParams = result.content
  console.log(params.approvalParams)
}

type User = (typeof users)[0]

const onRowClick = async (row) => {
  params.rowData = row
  try {
    const params = {
      apprNo: row.apprNo,
      sabun: row.sabun
    }
    console.log(params)
    // API 호출
    const result = await conveterNo(params)

    // 모달 무조건 열기
    isModalOpen.value = true

    // prcsNo 설정 (응답 구조에 맞게 수정)
    if (result?.prcsNo) {
      prcsNo.value = result.prcsNo
    } else {
      notyf.error('가격조사번호를 찾을 수 없습니다.')
    }

  } catch (e) {
    isModalOpen.value = true // 에러 시에도 모달 열기
    notyf.error(e.message)
  }
}


</script>

<template>
  <div class="page-content is-navbar-lg">
    <div>
      <div class="datatable-toolbar">
        <div class="column is-2">
          <VField class="pr-2">
            <VLabel class="has-fullwidth">
              결재제목
            </VLabel>
            <VControl>
              <input
                v-model="params.title"
                class="input custom-text-filter"
                placeholder="결재제목"
              >
            </VControl>
          </VField>
        </div>
        <div class="column is-8">
          <VField class="">
            <VLabel class="has-fullwidth">
              등록기간
            </VLabel>
            <VControl>
              <div class="columns">
                <div class="column is-6">
                  <VDatePicker
                    v-model.string="params.regSdt"
                    color="green"
                    :masks="masks"
                    trim-weeks
                  >
                    <template #default="{ inputValue, inputEvents }">
                      <VField>
                        <VControl icon="lucide:calendar">
                          <input
                            class="input v-input"
                            type="text"
                            :value="inputValue"
                            placeholder="시작일"
                            v-on="inputEvents"
                          >
                        </VControl>
                      </VField>
                    </template>
                  </VDatePicker>
                </div>
                <div class="column is-1" style="display: flex; align-items: center; justify-content: center;">
                  <span>~</span>
                </div>
                <div class="column is-6">
                  <VDatePicker
                    v-model.string="params.regEdt"
                    color="green"
                    :masks="masks"
                    trim-weeks
                  >
                    <template #default="{ inputValue, inputEvents }">
                      <VField>
                        <VControl icon="lucide:calendar">
                          <input
                            class="input v-input"
                            type="text"
                            :value="inputValue"
                            placeholder="종료일"
                            v-on="inputEvents"
                          >
                        </VControl>
                      </VField>
                    </template>
                  </VDatePicker>
                </div>
              </div>
            </VControl>
          </VField>
        </div>
        <div class="column is-2">
          <div style="margin-top: 1.8rem">
            <VButtons class="buttons is-right">
              <VButton
                color="primary"
                elevated
                icon="fas fa-search"
                @click.stop="searchApproval"
              >
                검색
              </VButton>
            </VButtons>
          </div>
        </div>
      </div>
      <div class="datatable-wrapper">
        <ComVFlexTable
          :data="params.approvalParams"
          :columns="params.flexColumn"
          :separators="true"
          :clickable="true"
          :compact="true"
          :use-approval-header="true"
          @row-click="onRowClick"
        >
        </ComVFlexTable>

        <!-- 모달 컴포넌트 추가 -->
        <VModal
          is="form"
          v-model:open="isModalOpen"
          title="결재함"
          size="contract-big"
          actions="center"
          @submit.prevent="isModalOpen = false"
          @close="isModalOpen = false"
        >
          <template #content>
            <PriceDetail :prcsNo="prcsNo" />
          </template>
          <template #action>
            <VButton type="submit" color="info" raised @click="updateIntegratedPaymentRejectionFunc">반려</VButton>
            <VButton type="submit" color="primary" raised @click="updateIntegratedPaymentApprovalFunc">승인</VButton>
          </template>
        </VModal>

        <VFlexPagination
            :item-per-page="itemsPerPage"
            :total-items="totalItems"
            v-model:current-page="currentPage"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.datatable-toolbar {
  padding: 1rem 1.5rem;
  margin: 0 0 2rem 0;
}

.flex-table .flex-table-item {
  min-height: 2rem;
  background-color: var(--primary);
  border: 0px;
}

input[readonly] {
  background-color: #f5f5f5;
  color: #888;
  cursor: not-allowed;
  border-color: #e0e0e0;
}

.v-buttons-right-align {
  display: flex;
  justify-content: flex-end;
  margin-top: 1rem; // 필요 시 간격 추가
}

.flex-table .flex-table-header {
  padding: 0.5rem;
}
.flex-table.is-table-clickable .flex-table-item:hover, .flex-table.is-table-clickable .flex-table-item:focus-within a:hover {
  background-color: var(--primary)!important;
}
</style>
