<script setup lang="ts">
import { h, shallowRef, watch, nextTick, ref } from "vue"
import { ElInputNumber } from "element-plus"
import BasicDescriptions from "/@/components/BasicDescriptions";
import { createTooltip } from "/@/utils/tootip";
import { useVModel } from "@vueuse/core"

import { division } from "/@/utils/calc";


const emit = defineEmits(['update'])
const props = defineProps<{ visible: boolean, data: any, index: number, mode: 'sale' | 'purchase' }>()

const visible  = useVModel(props, 'visible')
const openAmount = shallowRef(0)
const goodPrice = shallowRef(0)
const goodNum = shallowRef(0)


const detail = ref({})

const columns = [
  {
    field: 'sequenceNo',
    label: '采购单编号',
    span: 8
  },  
  {
    field: 'goodName',
    label: '商品名称',
    span: 16,
    render: (_, { goodNo, goodName }) => createTooltip(goodName, "商品编号 : " + goodNo, 300)
  },
  {
    field: '',
    label: '订单类目',
    span: 24,
    render: (_, { cat_code, cat_name }) => createTooltip(cat_name, "订单类目编号 : " + cat_code, 300)
  },
  {
    field: 'goodPrice',
    label: '单价',
    span: 8
  },
  {
    field: 'goodNum',
    label: '数量',
    span: 8
  },
  {
    field: '',
    label: '开票金额',
    span: 8,
    render(){
      return h(ElInputNumber, {
        size: 'small',
        modelValue: openAmount.value,
        max: props.data.balance_amount,
        min: 0,
        'onUpdate:modelValue': value => openAmount.value = value,
        controlsPosition: 'right',
        style: 'width:100%;',
        precision: 2
      })
    }
  }
]


watch(() => visible.value, () => {
  if(!visible.value) return
  nextTick(() => {
    detail.value = props.data
    openAmount.value = props.data.open_amount
  })
}, {
  immediate: true
})


// watch(() => [openAmount.value, goodNum.value], () => {
//   goodPrice.value = Number(division(openAmount.value, goodNum.value)).toFixed(2)
// })


function confirm(){
  emit('update', openAmount.value, goodNum.value ,props.index )
  visible.value = false
}

</script>


<template>
  <ElDialog 
    :title="`修改${props.mode === 'sale' ? '销售订单' : '采购单'}`" 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    v-model="visible" 
    center
    >
    <BasicDescriptions :columns="columns" :data="detail"  />
    <div class="flex justify-end mt-[10px]">
      <ElButton type="primary" @click="confirm">保存</ELButton>
    </div>
  </ElDialog>
</template>
