<script setup lang="ts">
import { ElForm } from "element-plus";
import { ref, watch, unref } from "vue";
import ChooseModal from "./choose-modal.vue";
import { createRules } from "../config/_rules";
import { useAsync } from "/@/hooks/core/useAsync";
import { httpDetail, httpOldDetail } from "/@/api/purchase/orderPay";
import BasicDescriptions from "/@/components/BasicDescriptions";
import {  PURCHASE_OLD_APPLY_DATE } from "/@/utils/constants" 

import { purchpayColumns, purchpayColumnsNew  } from "/@/utils/details/_purchase";

const emit = defineEmits(["create"]);


const isOld = ref(false)
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const chooseModalRef = ref<InstanceType<typeof ChooseModal> | null>(null);
const { data: detail, run: runDetail } = useAsync<Record<string, string>>({ initalData: {} });


const formData = ref({ dzNo: "", reason: "" });
const handleChoose = () => chooseModalRef.value.onDisplay();

const handleCreate = () => emit('create', formData.value, isOld.value)

function handleUpdate(dzNo, payNo){
  formData.value.dzNo = dzNo
  const date = payNo.slice(3, 9)
  isOld.value = date < PURCHASE_OLD_APPLY_DATE
  runDetail(isOld.value ? httpOldDetail({ DzNo: formData.value.dzNo }) : httpDetail({ dzNo: formData.value.dzNo }))
}
</script>

<template>
  <div w-full>
    <ElForm ref="formRef" :model="formData" :rules="createRules">
      <ElFormItem label="采购付款" prop="dzNo">
        <div class="w-full flex justify-end">
          <ElButton type="primary" text @click="() => handleChoose()">
            选择
          </ElButton>
        </div>

        <div class="w-full" v-if="Object.keys(detail).length > 0">
          <BasicDescriptions :columns="isOld ? purchpayColumns : purchpayColumnsNew" :data="detail" />
        </div>
      </ElFormItem>

      <ElFormItem label="退款原因" prop="reason">
        <ElInput v-model="formData.reason" placeholder="请输入退款原因" />
      </ElFormItem>

      <ElFormItem>
        <div class="flex w-full justify-end">
          <ElButton type="primary" @click="handleCreate">保存</ElButton>
        </div>
      </ElFormItem>
    </ElForm>

    <ChooseModal
      ref="chooseModalRef"
      @choose="handleUpdate"
    />
  </div>
</template>

<style lang="scss" scoped></style>
