<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="80%"
    :visible="visible"
    :maskClosable="false"
    :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: 3 }, xs: { span: 24 } }"
      :wrapper-col="{ md: { span: 20 }, sm: { span: 20 }, xs: { span: 24 } }"
    >
      <a-form-item label="标题" name="name">
        <div class="w-full flex justify-between">
          <a-input
            allow-clear
            :maxlength="20"
            placeholder="请输入标题"
            v-model:value="form.name"
          />
        </div>
      </a-form-item>
      <a-form-item label="内容" name="comments">
        <MdEditor v-model="form.comments" placeholder="请填写内容(已加密处理)，图片支持一键粘贴。" />
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
          :min="0"
          :max="99999"
          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 useFormData from '@/utils/use-form-data';
import {
  addProjectField,
  updateProjectField
} from '@/api/project/projectField';
import { message } from 'ant-design-vue/es';
import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
import { FileRecord } from '@/api/system/file/model';
import { uuid } from 'ele-admin-pro';
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import 'md-editor-v3/lib/preview.css';
import { ProjectField } from '@/api/project/projectField/model';
import {decrypt, encrypt} from "@/utils/common";
import DictSelect from "@/components/DictSelect/index.vue";
import {DictData} from "@/api/system/dict-data/model";

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

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

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

// 提交状态
const loading = ref(false);
const images = ref<ItemType[]>([]);
const id = 'preview-only';
const formRef = ref<FormInstance | null>(null);// 国际化

const { form, resetFields, assignFields } = useFormData<ProjectField>({
  id: undefined,
  type: undefined,
  appId: undefined,
  name: undefined,
  status: undefined,
  comments: '',
  sortNumber: 100
});

// 表单验证规则
const rules = reactive({
  type: [
    {
      required: true,
      type: 'number',
      message: '请选择字段类型'
    }
  ],
  // name: [
  //   {
  //     required: true,
  //     type: 'string',
  //     message: '请选择类型'
  //   }
  // ],
  value: [
    {
      required: true,
      type: 'string',
      message: '请填写字段值'
    }
  ],
  comments: [
    {
      required: true,
      type: 'string',
      message: '请输入内容'
    }
  ],
});

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

const chooseType = (item: DictData) => {
  form.name = item.dictDataCode;
  form.comments = item.comments;
};

const chooseImage = (data: FileRecord) => {
  images.value.push({
    uid: data.id,
    url: data.path,
    status: 'done'
  });
  form.comments = data.downloadUrl;
  form.type = 1;
};

const onDeleteItem = (index: number) => {
  images.value.splice(index, 1);
  form.type = 0;
};

/* 保存编辑 */
const save = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      const data = {
        ...form,
        appId: props.appId,
        comments: encrypt(form.comments)
      };
      const saveOrUpdate = isUpdate.value
        ? updateProjectField
        : addProjectField;
      saveOrUpdate(data)
        .then((msg) => {
          loading.value = false;
          message.success(msg);
          updateVisible(false);
          // 清除缓存
          if (form.name == 'i18n') {
            localStorage.setItem('i18n','1');
            window.location.reload();
          }
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    })
    .catch(() => {});
};

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      images.value = [];
      if (props.data) {
        assignFields(props.data);
        form.comments = decrypt(props.data.comments);
        if (form.type == 1) {
          images.value.push({
            uid: uuid(),
            url: props.data.comments,
            status: 'done'
          });
        }
        isUpdate.value = true;
      } else {
        isUpdate.value = false;
      }
    } else {
      form.comments = undefined
      // resetFields();
    }
  }
);
</script>
<style lang="less">
svg.md-editor-icon{
  width: 24px !important;
  height: 24px !important;
}
</style>
