<script setup lang="ts">
import { onMounted, PropType, ref } from "vue";
import { hTableAPI } from "@/api/hTable";
import { TableConfig, TableColumn } from "./hTable";
import { FormInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  //** 传入的表单数据 */
  id: {
    type: Number,
    default: -1,
  },
  tableData: {
    type: Object as PropType<TableConfig>,
    default: null,
  },
  row: {
    type: Object,
    default: null,
  },
  tagData: {
    type: Object,
    default: () => {},
  },
});
const emit = defineEmits(["handlePagedCallback"]);
const editFormRef = ref<FormInstance>();
const column = ref<Record<string, TableColumn>>({});
const editData = ref({
  frorm: {},
  isedit: props.id !== -1,
  table: props.tableData,
  rules: [
    {
      required: true,
      message: "不能为空",
      trigger: "blur",
    },
  ],
  formLabelWidth: "120px",
  size: "small",
  loading: false,
});
const Api = new hTableAPI(editData.value.table.apiUrl);
onMounted(() => {
  intiColumn();
  fetchInitData();
  fetchFormData();
});

function execute(obj, btn) {
  return eval(obj);
}
function intiColumn() {
  for (const key in editData.value.table.column) {
    const element = editData.value.table.column[key];
    if (editData.value.isedit) {
      if (element.edit) {
        column.value[key] = element;
      }
    } else {
      if (element.add) {
        column.value[key] = element;
      }
    }
  }
}
function handlePagedCallback() {
  emit("handlePagedCallback"); // 传参给父组件
}
function handleSubmitForm() {
  editFormRef.value.validate((valid) => {
    if (!valid) {
      return;
    }

    editData.value.loading = true;
    let form: any = {};
    if (editData.value.isedit) {
      form = props.row;
    } else form.id = 0;
    for (const key in column.value) {
      const element = column.value[key];
      if (element.valueE !== null && element.valueE !== "") {
        form[key] = element.valueE;
      }
    }
    if (editData.value.table.editCallback) {
      editData.value.table.editCallback(form);
    }
    Api.edit(form).then((res) => {
      editData.value.loading = false;
      if (res.code === 200) {
        ElMessage.success("操作成功");
        setTimeout(handlePagedCallback, 0);
      } else {
        ElMessage.error(res.message);
      }
    });
  });
}
function handleResetForm() {
  for (const key in column.value) {
    let item = column.value[key];
    if (Array.isArray(item.valueE)) {
      item.valueE = [];
    } else if (typeof item.valueE === "number") {
      item.valueE = "";
    } else if (typeof item.valueE === "boolean") {
      item.valueE = false;
    } else {
      item.valueE = "";
    }
  }
}
function fetchInitData() {}
function fetchFormData() {
  editData.value.loading = false;
  if (editData.value.isedit) {
    handleResetForm();
    Api.Info(props.id).then((res) => {
      if (res.code === 200) {
        editData.value.frorm = res.data;
        for (const key in column.value) {
          const element = column.value[key];
          element.valueE = res.data[key];
        }
      }
      editData.value.loading = true;
    });
  } else {
    editData.value.loading = true;
  }
}
</script>

<template>
  <div>
    <el-form
      v-if="editData.loading"
      ref="editFormRef"
      :model="editData.table.column"
      :label-width="editData.formLabelWidth"
      clearable
    >
      <el-form-item
        v-for="(o, k, i) in column"
        v-show="execute(o['editShow'], o)"
        :key="i"
        :rules="o.rules"
        :prop="'' + k + '.valueE'"
        :label="o.label"
      >
        <div v-if="o.type.trim() == 'datetime'">
          <el-date-picker
            v-model="o.valueE as Date"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :placeholder="o.label"
            class="elWidth"
            @change="o.change"
          />
        </div>
        <div v-else-if="o.type.trim() == 'dropdown'">
          <el-select
            v-model="o.valueE"
            :multiple="o.multiple"
            clearable
            filterable
            :placeholder="o.label"
            class="elWidth"
            @change="o.change"
          >
            <el-option
              v-for="item in o.setting.datasource"
              :key="item.value"
              autocomplete="off"
              :label="item[o.setting.maplabel]"
              :value="item[o.setting.mapValue]"
            />
          </el-select>
        </div>
        <div v-else-if="o.type.trim() == 'textarea'">
          <el-input
            v-model="o.valueE as string"
            :rows="o.editRows || 4"
            type="textarea"
            :placeholder="o.label"
            class="elWidth"
            @change="o.change"
          />
        </div>
        <div v-else-if="o.type.trim() == 'switch'">
          <el-switch
            v-model="o.valueE as boolean"
            active-text="启用"
            inactive-text="禁用"
            class="elWidth"
            @change="o.change"
          />
        </div>
        <div v-else>
          <el-input v-model="o.valueE as string" class="elWidth" :placeholder="o.label" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="!editData.loading" @click="handleSubmitForm()"
          >立即提交</el-button
        >
        <el-button @click="handleResetForm()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style>
.elWidth {
  width: 100%;
  min-width: 220px;
}
</style>
