<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="500"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
    @opened="dialogOpened"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="rules"
      :labelWidth="140"
      colon
    >
      <t-form-item
        v-for="item in columns"
        :key="item.colKey"
        :label="item.title"
        :name="rules[item.colKey] ? item.colKey : undefined"
      >
        <SearchFormItem
          :item="{ ...item.comp, prop: item.colKey, label: item.title }"
          :params="formData"
        />
      </t-form-item>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>
<script setup name="EditColumnDialog">
import { ref, computed } from 'vue';
// import { MessagePlugin } from 'tdesign-vue-next';
import SearchFormItem from '@/components/global/search-form/components/search-form-item.vue';

const emit = defineEmits(['update:visible', 'success']);
const props = defineProps({
  visible: Boolean,
  curRow: Object,
  columns: Array,
});

const formRef = ref(null);
const formData = ref({});

const title = computed(() => {
  return (props.curRow?.key ? '编辑' : '新增') + '数据';
});

const rules = computed(() => {
  let rules = {};
  props.columns
    .filter((item) => !!item.rules)
    .forEach((item) => {
      rules[item.colKey] = item.rules;
    });
  return rules;
});

const dialogOpened = () => {
  formData.value = { ...props.curRow };
};

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  // MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success', formData.value);
};
</script>
