<script setup lang="ts">
import { computed, ref, unref, watchEffect } from "vue";
import BasicDescriptions from "/@/components/BasicDescriptions";
import { order_detail_columns } from "./columns";

const visible = ref(false);
const data = ref<Record<string, string>>({});
const emit = defineEmits(["save-btn-click"]);

const total = ref(0);
const inv_fee = ref(0);

function handleSave() {
  visible.value = false;

  emit("save-btn-click", {
    row: unref(data),
    inv_fee: unref(inv_fee),
    num: unref(total)
  });
}

const totalNum = computed(() => {
  const { winv_num } = data.value as any;
  return winv_num;
});

watchEffect(() => {
  total.value = totalNum.value;
});

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) {
  const { goodPrice } = data.value
  total.value = Number(accDiv(value, goodPrice)).toFixed(8)
}


defineExpose({
  onDisplay({ row: _data }) {
    visible.value = true;
    data.value = _data;
    inv_fee.value = data.value.winv_fee as any;
  }
});
</script>

<template>
  <el-dialog v-model="visible" title="编辑销售订单" center width="1040px" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <BasicDescriptions :data="data" :col-number="2" :columns="order_detail_columns">
      <template #custom>
        <el-row>
          <!-- <div class="col-item" style="width: 247px">
            <p class="col-label">开票数量</p>
            <p class="col-value">
              <el-input-number
                size="small"
                placeholder="开票数量"
                :min="0.1"
                style="width: 100%"
                :max="totalNum"
                v-model="total"
              />
            </p>
          </div> -->

          <div class="col-item" style="width: 247px">
            <p class="col-label">开票数量</p>
            <p class="col-value">
              {{ total }}
            </p>
          </div>

          <div class="col-item" style="width: 248px">
            <p class="col-label">开票金额</p>
            <p class="col-value">
              <el-input-number placeholder="开票金额" :precision="2" :min="0.1" size="small" style="width: 100%" :max="data.winv_fee"
                v-model="inv_fee" @change="handleTotalChange" />
            </p>
          </div>
        </el-row>
      </template>
    </BasicDescriptions>

    <div flex w-full justify-end mt-2>
      <el-button size="small" type="primary" @click="handleSave">保存</el-button>
    </div>
  </el-dialog>
</template>
