<template>
  <Panel title="服务项目">
    <el-table v-if="itemDetail.length>0" :data="itemDetail" max-height="150">
      <el-table-column prop="itemName" label="项目名称" show-overflow-tooltip></el-table-column>
      <el-table-column label="单价">
        <template #default="scope">
          ￥{{ scope.row.selectedPrice }}
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template #default="scope">
          <el-input-number v-if="disabled||props.status==0" v-model="scope.row.selectedNum" min="0"
                           @change="handleNumChange" size="small"></el-input-number>
          <span v-else>{{ scope.row.selectedNum }}</span>
          {{ scope.row.selectedUnit }}
        </template>
      </el-table-column>
      <el-table-column label="小计">
        <template #default="scope">
          ￥{{ scope.row.selectedNum * scope.row.selectedPrice }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="danger" link @click="delService(scope.row)">X</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom">
      <SearchInput :request-api="serviceSearchApi"
                   :show-config="serviceShowConfig"
                   :disabled="!disabled"
                   @selectedCallBack="serviceSelect"></SearchInput>
      <span>合计：￥{{ getTotalPrice() || 0 }}</span>
    </div>
  </Panel>
</template>
<script setup lang="ts">
import {defineProps, watchEffect, ref} from "vue";
import SearchInput from "@/components/SearchInput.vue";
import Panel from "@/components/common/Panel.vue";

const props = defineProps({
  status: {
    type: Number,
    default: 0
  }
})
const itemDetail = defineModel<any>();

const delService = (item: any) => {
  itemDetail.value = itemDetail.value.filter((i: any) => i.id != item.id)
}
const serviceSearchApi = "item/search";
const serviceShowConfig = [
  {
    label: "服务名称",
    prop: "itemName",
  },
  {
    label: "服务医保码",
    prop: "itemSocialCode",
  },
  {
    label: "售价",
    prop: "unitPrice",
  },
]
const emit = defineEmits(['totalPriceChange'])
const serviceSelect = (row: any) => {
  row.selectedNum = 1
  row.selectedUnit = row.unit
  row.selectedPrice = row.unitPrice
  itemDetail.value.push(row)
  emit('totalPriceChange')
}
const handleNumChange = () => {
  emit('totalPriceChange')
}

const getTotalPrice = () => {
  let totalPrice = 0;
  if (itemDetail.value) {
    itemDetail.value.forEach((item: any) => {
      totalPrice += item.selectedNum * item.selectedPrice
    })
  }

  return totalPrice;
}
const disabled = ref<any>(false)

watchEffect(() => {
      if (props.status == 2 || props.status == 0) {
        disabled.value = true
      } else {
        disabled.value = false
      }
    }
)
</script>
<style scoped lang="scss">
:deep(.el-table__cell) {
  padding: 0 4px;
}

.bottom {
  text-align: right;
}
</style>