<style scoped lang="scss">

</style>
<template>
  <div class="system-dialog-container">
    <el-dialog
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        width="820px"
        draggable
        destroy-on-close
        :close-on-click-modal="false"
        align-center>
      <ext-detail-form
          ref="formRef"
          label-position="right"
          v-model="state.ruleForm"
          :columns="state.columns"
          :rules="state.rules"
          @on-change="handleFormChange"
      ></ext-detail-form>

      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button :loading="state.btnLoading" type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="ConfigDialog">
import {defineAsyncComponent, reactive, onMounted, ref} from 'vue';
import {Msg} from "/@/utils/message";
import {$body, $get} from "/@/utils/request";
import u from '/@/utils/u'

// 引入组件
const ExtDetailForm = defineAsyncComponent(() => import('/@/components/form/ExtDetailForm.vue'));

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const formRef = ref();
//定义初始变量，重置使用
const initState = ()=>({
  ruleForm: {
    id:0
  },
  btnLoading: false,
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  columns: [
    {label: '字段', prop: 'code', type: 'text',readonly:true},
    {
      label: '状态',
      prop: 'status',
      type: 'dict',
      conf: {dict: 'Common.status'}
    },
    {label: '值', prop: 'value', type: 'textarea',},
    {label: '描述', prop: 'remark', type: 'textarea',},
  ],
  rules: {},
})

// 定义变量内容
const state = reactive(initState());


// 打开弹窗
const open = (action: string='add', row: any) => {
  state.dialog.title = u.dialog.actions[action].title +"『应用配置』"
  state.dialog.submitTxt = u.dialog.actions[action].btn +"『应用配置』"
  state.dialog.isShowDialog = true;
  if (action !=='add') {
    loadData(row.id);
  }
};
// 关闭弹窗
const onClose = () => {
  state.dialog.isShowDialog = false;
  Object.assign(state,initState())
};
// 取消
const onCancel = () => {
  onClose();
};
// 提交
const onSubmit = () => {
  formRef.value.checkForm().then(() => {
    state.btnLoading = true;
    const url = state.ruleForm.id > 0 ? "config/modify" : "config/add"
    $body(url, state.ruleForm).then(() => {
      state.btnLoading = false;
      Msg.message('操作成功');
      console.log('submit!')
      onClose();
      emit('refresh');
    })
  }).catch(() => {
    state.btnLoading = false;
    Msg.message('请完整填写表单', 'error');
  })
};

const handleFormChange = (formData: any) => {
  console.log(formData)
}

// 初始化表格数据
const loadData = (id: number) => {
  $get(`config/detail/${id}`).then((res: any) => {
    state.ruleForm = res;
  })
}

// 暴露变量
defineExpose({
  open
});


</script>