<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import { addSysConfig, updateSysConfig } from '#/api'

const props = defineProps({
  showDia: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '查看',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})

const emit = defineEmits(['update:showDia', 'onRefresh'])

const show = computed({
  get() {
    return props.showDia
  },
  set(val) {
    emit('update:showDia', val)
  },
})
const showTool = computed(() => props.title !== '查看')

const rules = {
  code: {
    required: true,
    message: '请填写编码',
    trigger: 'blur',
  },
  name: {
    required: true,
    message: '请填写名称',
    trigger: 'blur',
  },
  value: {
    required: true,
    message: '请填写值',
    trigger: 'blur',
  },
}

const form = ref({
  code: '',
  name: '',
  value: '',
})
const ruleFormRef = ref<FormInstance>()

watch(
  () => props.showDia,
  async (newVal) => {
    form.value = {
      code: '',
      name: '',
      value: '',
    }
    show.value = newVal
    if (props.diaData.code && newVal) {
      const { code, name, value } = props.diaData
      form.value = { code, name, value }
    }
  },
)

async function handleSave(formEl: FormInstance | undefined) {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      await (props.title === '新增'
        ? addSysConfig({ ...form.value })
        : updateSysConfig({ id: props.diaData.id, ...form.value }))
      emit('onRefresh')
      show.value = false
    } else {
      ElMessage.error('请输入编码或名称')
    }
  })
}
async function onClose() {
  // let flag = false;
  // for (let key in form.value) {
  //     if ((form.value as anyObj)[key] !== props.diaData[key]) {
  //         flag = true;
  //         break;
  //     }
  // }
  // if (flag) {
  //     await delConfirm(true);
  // }
  show.value = false
}
</script>

<template>
  <el-dialog
    v-model="show"
    :title="title"
    width="500px"
    class="box"
    destroy-on-close
    :before-close="onClose"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      label-width="80px"
      :rules="rules"
      :disabled="!showTool"
    >
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="form.name" :disabled="title === '编辑'" />
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="form.code" :disabled="title === '编辑'" />
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input
          v-model="form.value"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 10 }"
        />
      </el-form-item>
    </el-form>
    <template v-if="showTool" #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">关闭</el-button>
        <el-button type="primary" @click="handleSave(ruleFormRef)">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
