<template>
  <el-dialog :model-value="visible" :title="data._id ?'编辑诊查费':'新增诊查费'" @close="close" :width="width">
    <el-form class="p-15px">
      <el-form-item class="is-required" label="名称" prop="name">
        <el-input clearable v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item class="is-required" label="编码" prop="code">
        <el-input clearable v-model="form.code" placeholder="请输入编码" />
      </el-form-item>
      <el-form-item class="is-required" label="金额" prop="fee">
        <el-input clearable v-model="form.fee" placeholder="请输入金额">
          <template #append>元</template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" @click="close()">取消</el-button>
        <el-button class="w-100px" type="primary" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { useHlw } from "@/api/hlw";
import { verifyString, verifyNumber, verifyListItem } from '@/utils/index'

const emits = defineEmits(["close", "change"]);
const props = defineProps({
  data: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
  width: { type: Number, default: 300 },
});

const form = ref({})

function close() {
  emits("close");
};

async function save() {
  const [namePass, name] = verifyString(form.value.name, '名称', 1, 50);
  if (!namePass) {
    ElMessage.info(name);
    return;
  };
  const [codePass, code] = verifyString(form.value.code, '编码', 1, 50);
  if (!codePass) {
    ElMessage.info(code);
    return;
  };
  const [feePass, fee] = verifyNumber(form.value.fee, '金额', 2, 0, 999999,true);
  if (!feePass) {
    ElMessage.info(fee);
    return;
  };
  const params = { code, name, fee };
  if (props.data._id) {
    params.id = props.data._id;
  }
  const apiName = props.data._id ? 'editHlwChargeItem' : 'addHlwChargeItem';
  const { success, message } = await useHlw({ type: apiName, ...params });
  if (success) {
    ElMessage.success(message);
    emits("change");
    close()
  } else {
    ElMessage.error(message)
  }
}

watch(() => props.visible, (val) => {
  if (val) {
    console.log(props.data, typeof props.data.fee)
    form.value.name = typeof props.data.name === 'string' ? props.data.name.trim() : '';
    form.value.code = typeof props.data.code === 'string' ? props.data.code.trim() : '';
    form.value.fee = typeof props.data.fee === 'number' ? props.data.fee : '';
    console.log(form.value)

  }
})

</script>