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

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

const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const chooseModalRef = ref<InstanceType<typeof ChooseModal> | null>(null);
const formData = ref<Record<string, any>>({
  hpNo: "",
  reason: ""
});

const { run: runDetail, data: detail } = useAsync({
  initalData: {}
});

const handleChoose = () => chooseModalRef.value.onDisplay();

function handleCreate() {
  formRef.value.validate(isValid => isValid && emit("create", unref(formData)));
}

watch(
  () => formData.value.hpNo,
  hpNo => runDetail(httpDetail({ hpNo }))
);
</script>

<template>
  <div w-full>
    <ElForm
      ref="formRef"
      label-width="100px"
      :model="formData"
      :rules="createRules"
    >
      <ElFormItem label="采购开票" prop="hpNo">
        <div class="w-full flex justify-end">
          <ElButton type="primary" link @click="handleChoose">选择</ElButton>
        </div>

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

      <ElFormItem label="解除原因" prop="reason">
        <ElInput
          style="width: 350px"
          type="textarea"
          v-model="formData.reason"
        />
      </ElFormItem>

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

    <ChooseModal
      ref="chooseModalRef"
      @choose="hpNo => (formData.hpNo = hpNo)"
    />
  </div>
</template>
