<script setup lang="ts">
import { reactive, ref, unref } from "vue";
import { ElForm } from "element-plus";
import { CAPITAL_COLUMNS } from "/@/utils/details/tragelog";
import { httpTradeDetail } from "/@/api/InvoiceSales/refund";
import { useResponseHandle } from "/@/hooks";
import CapitalModal from "./capital-modal.vue";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { createRules } from "../config/_rules";

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

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 formRules = reactive({ ...createRules });

const formData = reactive({
  logNo: "",
  type: "2",
  return_reason: ""
});

async function requesetCapitalDetail(logNo) {
  loading.value = true;
  const { code, message, data } = await httpTradeDetail({
    logNo
  });

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

function handleCreate() {
  formRef.value.validate(async isVaild => {
    if (!isVaild) return;
    emit("create", unref(formData));
  });
}
</script>
<template>
  <el-form
    :rules="formRules"
    :model="formData"
    ref="formRef"
    size="small"
    label-width="100px"
  >
    <el-form-item label="资金认领" prop="logNo">
      <div flex justify-end w-full mb-2>
        <el-button
          size="small"
          type="primary"
          @click="() => capitalModalRef.onDisplay()"
          >选择</el-button
        >
      </div>

      <BasicDescriptions
        w-full
        v-loading="loading"
        v-if="capitalDetail"
        :data="capitalDetail"
        :col-number="2"
        :columns="CAPITAL_COLUMNS"
      />
    </el-form-item>

    <!-- <el-form-item label="申请类型" prop="type">
      <el-select v-model="formData.type" placeholder="请选择申请类型" w-380px>
        <el-option value="2" label="解除资金认领" />
      </el-select>
    </el-form-item> -->

    <el-form-item label="退款原因" prop="return_reason" w-480px>
      <el-input v-model="formData.return_reason" placeholder="请输入退款原因" />
    </el-form-item>

    <div flex w-full justify-end>
      <el-button type="primary" @click="handleCreate">保存</el-button>
    </div>
  </el-form>

  <CapitalModal
    ref="capitalModalRef"
    @on-add-order="({ logNo }) => requesetCapitalDetail(logNo)"
  />
</template>
