<template>
  <a-modal
    :open="visible"
    title="修改公告"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
       ref="formRef"
      :model="formState"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item ref="title" label="标题" name="title">
        <a-input v-model:value="formState.title" />
      </a-form-item>
      <a-form-item name="content" label="内容" >
        <a-textarea v-model:value="formState.content" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { message } from '@hwork/ant-design-vue';
import { edit } from "@/api/module/announce";
import { defineComponent, reactive, ref, toRaw, watch } from "vue";
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    }
  },
  emit: ["close"],
  setup(props, context) {

    const formRef = ref();
    
    const formState = reactive({});

    watch(props, (props) => {
        formState.id = props.record.id
        formState.title = props.record.title
        formState.content = props.record.content
    })

    const formRules = {
      name: [ { required: true, message: '请输入公告标题', trigger: 'blur'} ],
      code: [ { required: true, message: '请输入公告内容', trigger: 'blur'} ]
    };

    const editKey = "add";

    const submit = (e) => {
      formRef.value
      .validate()
      .then(() => {
          message.loading({ content: '提交中...', key: editKey });
          edit(toRaw(formState)).then((response)=>{
              if(response.success){
                message.success({ content: '保存成功', key: editKey, duration: 1 }).then(()=>{
                  cancel();
                });
              }else{
                message.success({ content: '保存失败', key: editKey, duration: 1 }).then(()=>{
                  cancel();
                });
              }
          });
        })
        .catch(error => {
          console.log('error', error);
        });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };

    return {

      submit,
      cancel,
      formRef,
      formState,
      formRules,
      
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
  },
});
</script>