<script setup lang="ts">
import { reactive, ref, unref } from "vue";
import { ElForm } from "element-plus";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { httpDetail } from "/@/api/InvoiceSales/invoiceApply";
import { ORDER_COLUMNS } from "/@/utils/details/inv-open";
import { useResponseHandle } from "/@/hooks/core/useAsync";
import { createRules } from "../config/_rules";
import CapitalModal from "./capital-modal/index.vue";
import Invoice from "/@/components/Invoice";

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

const invNumber = ref("");
const openDate = ref("");
const capitalModalRef = ref<InstanceType<typeof CapitalModal>>(null);
const capitalDetail = ref<Record<string, string | null>>(null);
const formRef = ref<InstanceType<typeof ElForm>>(null);
const responseHandle = useResponseHandle();
const loading = ref(false);

const formData = reactive({
  invNo: "",
  return_reason: "",
  remark: ""
});

async function requesetCapitalDetail({ invNo, inv_number, open_date }) {
  loading.value = true;
  invNumber.value = inv_number;
  openDate.value = open_date;

  const { code, message, data } = await httpDetail({
    invNo
  });

  responseHandle({
    code,
    message,
    handler: function () {
      capitalDetail.value = data;
      formData.invNo = data.invNo;
      formRef.value.validateField("logNo");
    }
  });
  loading.value = false;
}

function handleCreate() {
  formRef.value.validate(async isValid => {
    if (!isValid) return;
    emit("create", unref(formData));
  });
}
</script>
<template>
  <ElForm
    ref="formRef"
    :model="formData"
    :rules="createRules"
    size="small"
    label-width="100px"
  >
    <ElFormItem label="发票" prop="invNo">
      <div class="flex justify-end w-full mb-2">
        <ElButton
          size="small"
          type="primary"
          @click="() => capitalModalRef.onDisplay()"
          >选择</ElButton
        >
      </div>

      <BasicDescriptions
        w-full
        v-loading="loading"
        v-if="capitalDetail"
        :data="capitalDetail"
        :columns="ORDER_COLUMNS"
      />
    </ElFormItem>

    <Invoice v-if="invNumber" :inv-number="invNumber" type="sale" />

    <div mt-5 />

    <ElFormItem label="退票原因" prop="return_reason" w-480px>
      <ElInput
        type="textarea"
        :rows="6"
        maxlength="2000"
        max
        w-300px
        v-model="formData.return_reason"
        show-word-limit
      />
    </ElFormItem>

    <ElFormItem label="备注" prop="remark" w-480px>
      <ElInput
        type="textarea"
        :rows="6"
        maxlength="2000"
        v-model="formData.remark"
        placeholder="请输入发票备注"
        show-word-limit
      />
    </ElFormItem>

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

  <CapitalModal
    ref="capitalModalRef"
    @choose="row => requesetCapitalDetail(row)"
  />
</template>
