<script setup lang="ts">
import { shallowRef, h, getCurrentInstance, ref } from "vue";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { ElButton, ElDialog, ElInputNumber } from "element-plus";

const vm = getCurrentInstance();
const visible = shallowRef(false);
const emit = defineEmits(['save']);

const descriptionData = ref<Record<string, any>>({});

const columns = [
  { field: "sequenceNo", label: "销售单编号", span: 6 },
  { field: 'cxCode', label: '销售单主编号', span: 6 },
  { field: 'goodNo', label: '商品编码', span: 6 },
  { field: 'goodPrice', label: '商品单价' },
  { field: 'goodName', label: '商品名称', span: 24 },
  { field: 'goodNum', label: '商品总数量', span: 8 },
  { field: 'ainv_num', label: '已开票数量', span: 8 },
  { field: 'winv_num', label: '未开票数量', span: 8 },
  { field: 'totalPrice', label: '订单总金额', span: 8 },
  { field: 'ainv_fee', label: '已开票金额', span: 8 },
  { field: 'winv_fee', label: '未开票金额', span: 8 },
  { label: '本次开票数量', span: 8, render() { return descriptionData.value.num } },
  { label: '本次开票金额', span: 8, render(_, row) {
      return h(ElInputNumber, {
        precision: 2,
        min: 0,
        max: row.winv_fee,
        size: "small",
        'controls-position': 'right',
        modelValue: descriptionData.value.inv_fee,
        onChange: handleTotalChange
      })
    }
  }
]

function accDiv(arg1, arg2) {
  var r1 = arg1.toString(), r2 = arg2.toString(), m, resultVal, d = arguments[2];
  m = (r2.split(".")[1] ? r2.split(".")[1].length : 0) - (r1.split(".")[1] ? r1.split(".")[1].length : 0);
  resultVal = Number(r1.replace(".", "")) / Number(r2.replace(".", "")) * Math.pow(10, m);
  return typeof d !== "number" ? Number(resultVal) : Number(resultVal.toFixed(parseInt(d)));
}

function handleTotalChange(value: any) {
  descriptionData.value.inv_fee = value
  descriptionData.value.num = Number(accDiv(descriptionData.value.inv_fee, descriptionData.value.goodPrice)).toFixed(8);
}

function handleSave() {
  emit('save', descriptionData.value)
  visible.value = false;
}

defineExpose({
  onDisplay: (data: Record<string, any>) => {
    visible.value = true;
    descriptionData.value = {
      ...data,
      num: data.num,
      inv_fee: data.inv_fee,
      totalOpenAmount: data.totalOpenAmount
    };

  }
})
</script>


<template>
  <ElDialog width="1024px" v-model="visible" title="编辑采购单" center :close-on-click-modal="false"
  :close-on-press-escape="false">
    <BasicDescriptions :data="descriptionData" :columns="columns" />

    <div class="flex justify-end w-full">
      <ElButton type="primary" @click="handleSave">
        保存
      </ElButton>
    </div>
  </ElDialog>
</template>
