<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="1000"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑资料' : '添加资料'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ md: { span: 2 }, sm: { span: 4 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 21 }, sm: { span: 22 }, xs: { span: 24 } }"
    >
      <a-form-item label="名称" name="name">
        <a-input allow-clear placeholder="字段名称" v-model:value="form.name" />
      </a-form-item>
      <a-form-item label="资料" name="comments">
        <!-- 编辑器 -->
        <byte-md-editor
          v-model:value="form.comments"
          placeholder="资料内容"
          :locale="zh_Hans"
          mode="split"
          :plugins="plugins"
          height="300px"
          maxLength="500"
          :editorConfig="{ lineNumbers: true }"
        />
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
          :min="0"
          :max="99999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { CompanyField } from '@/api/oa/company/field/model';
  import useFormData from '@/utils/use-form-data';
  import { decrypt, encrypt } from '@/utils/common';
  import { addCompanyField, updateCompanyField } from '@/api/oa/company/field';
  import { message } from 'ant-design-vue/es';
  import zh_Hans from 'bytemd/locales/zh_Hans.json';
  import gfm from '@bytemd/plugin-gfm';
  import zh_HansGfm from '@bytemd/plugin-gfm/locales/zh_Hans.json';
  import highlight from '@bytemd/plugin-highlight';

  // 是否是修改
  const isUpdate = ref(false);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    companyId: number | null | undefined;
    // 修改回显的数据
    data?: CompanyField | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);

  const formRef = ref<FormInstance | null>(null);

  const { form, resetFields, assignFields } = useFormData<CompanyField>({
    id: undefined,
    companyId: undefined,
    name: '',
    comments: '',
    status: 0,
    sortNumber: 0
  });

  // 表单验证规则
  const rules = reactive({
    comments: [
      {
        required: true,
        type: 'string',
        message: '请填写内容'
      }
    ],
    name: [
      {
        required: true,
        message: '请输入名称'
      }
    ]
  });

  // 插件
  const plugins = ref([
    gfm({
      locale: zh_HansGfm
    }),
    highlight()
  ]);

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const data = {
          ...form,
          companyId: props.companyId
        };
        // 加密信息处理
        if (form.comments != '') {
          data.comments = encrypt(form.comments);
        } else {
          data.comments = undefined;
        }
        const saveOrUpdate = isUpdate.value ? updateCompanyField : addCompanyField;
        console.log(isUpdate.value);
        saveOrUpdate(data)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          const comments = decrypt(props.data.comments);
          assignFields(props.data);
          form.comments = comments;
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
