<script setup lang="ts">
import { ref ,computed} from "vue";
import { ElForm } from "element-plus";
import { httpUpdate } from "/@/api/InvoiceSales/updateInvoice";
import { ElMessageBox  } from "element-plus"


const emits = defineEmits(["refresh"])

const formData = ref({
  id: "",
  invNo: "",
  status: ""
})

const visible = ref(false);
const loading = ref(false);
const openType = ref("0");
const formRef = ref<InstanceType<typeof ElForm> | null>(null);


const options = computed(() => [
  ...openType.value === "0" ? [{ value: "0", label: "重新开票" }] : [],
  { value: "1", label: "重新获取开票信息" }
])

const rules = {
  status: [{ required: true, message: "请选择状态",  trigger: 'change' }],
  id: [{ required: true, message: '请选择一条开票申请', trigger:'change' }]
};

async function handleSave() { 
  loading.value = true;
  try {
    await formRef.value?.validate();
    const { id, status } = formData.value;
    const callback = async () => { 
        const response = await httpUpdate({ id, status });
        if (Number(response.code) !== 0) return
        visible.value = false;
        emits('refresh')
    }

    if (Number(status) === 0) {
      ElMessageBox.confirm("注意下大象后台是否已经开出 ", {
        type:'warning',
        confirmButtonText: "确认",
        cancelButtonText: "取消"
      }).then(async () => {
        await callback();
      })
    } else { 
      await callback();
    }
  } catch( err ) {
    console.log(err);
  } finally { 
    loading.value = false
  }
}

defineExpose({
  onDisplay: row => {
    const { id, invNo, KPFS } = row;
    openType.value = String(KPFS);
    formData.value = { id,status:"", invNo };
    visible.value = true;
  }
});
</script>

<template>
  <el-dialog
    v-model="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    title="修改金税开票"
    center
  >
    <el-form ref="formRef" size="small" label-width="120px" :rules="rules" :model="formData">
     <el-form-item label="开票申请编号" prop="id">
       <el-input v-model="formData.invNo" disabled />
     </el-form-item>

     <el-form-item label="状态" prop="status">
       <el-select class="w-full" v-model="formData.status" placeholder="请选择状态">
         <!-- <el-option label="重新开票" value="0"  /> -->
         <el-option v-for="opt in options" :label="opt.label" :value="opt.value" />
       </el-select>
      </el-form-item>

      <el-form-item>
        <div  class="w-full flex justify-end">
          <el-button type="primary" :loading="loading" @click="handleSave">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
