<script setup>
import { ref, nextTick, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import mitt from "@/utils/mitt.js";

const dialogVisible = ref(false);

const priceRef = ref(null);
const allPrice = ref(0);
const show = (e=true, p = 0) => {
  priceInfo.value.nowPrice = "";
  priceInfo.value.percentage = "";
  dialogVisible.value = e;
  allPrice.value = p;
  nextTick(() => {
    setTimeout(() => {
      priceRef.value?.focus();
    }, 150);
  });
};

const priceInfo = ref({
  nowPrice: "",
  percentage: "",
});

const inputPrice = (e) => {
  priceInfo.value.percentage = ((e / allPrice.value) * 100).toFixed(2);
};
const inputPercentage = (e) => {
  priceInfo.value.nowPrice = ((allPrice.value * e) / 100).toFixed(2);
};

const emit = defineEmits(["changeAllPrice"]);
const submitPrice = () => {
  if (priceInfo.value.percentage > 100) {
    priceInfo.value.nowPrice = "";
    priceInfo.value.percentage = "";
    return ElMessage.error("改价金额不能大于当前订单金额");
  }
  if (priceInfo.value.nowPrice <= 0) {
    priceInfo.value.nowPrice = "";
    priceInfo.value.percentage = "";
    return ElMessage.error("金额不能小于0");
  }
  emit("changeAllPrice", priceInfo.value.nowPrice);
};

defineExpose({
  show,
  dialogVisible,
});

// 键盘事件
const aenter = () => {
  if (dialogVisible.value) submitPrice();
};
onMounted(() => {
  mitt.on("enter", aenter);
});

onUnmounted(() => {
  mitt.off("enter", aenter);
});
</script>

<template>
  <el-dialog v-model="dialogVisible" title="订单改价" width="650">
    <div class="price">
      <div class="flex">
        <el-input
          ref="priceRef"
          style="flex: 3; margin: 0.625rem; height: 2.5rem"
          v-model="priceInfo.nowPrice"
          type="number"
          placeholder="请输入改价后的价格"
          @input="inputPrice"
        >
          <template #suffix>元</template>
        </el-input>
        <el-input
          style="flex: 2; margin: 0.625rem; height: 2.5rem"
          v-model="priceInfo.percentage"
          type="number"
          placeholder="请输入比例"
          @input="inputPercentage"
        >
          <template #suffix>%</template>
        </el-input>
      </div>
      <div style="margin: 0.625rem; padding-bottom: 40px">
        改价后金额:
        <span style="color: #f5222d; font-weight: bold; margin-left: 1rem"
          >¥{{ priceInfo.nowPrice || allPrice || " - - " }}</span
        >
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button class="ok-btn" type="primary" @click="submitPrice">
          确定 (Enter)
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.dialog-footer {
  .ok-btn {
    width: 100%;
    height: 2.5rem;
    border-radius: 2.5rem;
  }
}
.price {
  border-top: 1px solid #eee;
  padding-top: 1rem;
  .flex {
    display: flex;
  }
}
</style>
