<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form
        class="ls-form"
        ref="formRef"
        :model="formData"
        label-placement="left"
        label-width="100px"
      >
        <n-form-item
          label="字典项名"
          path="name"
          :rule="{ required: true, message: '请输入字典项名称', trigger: 'blur' }"
        >
          <n-input
            class="ls-input"
            v-model:value="formData.name"
            placeholder="请输入字典项名称"
            clearable
          />
        </n-form-item>
        <n-form-item label="字典项值" path="value">
          <n-input
            class="ls-input"
            v-model:value="formData.value"
            placeholder="请输入字典项值"
            clearable
          />
        </n-form-item>
        <n-form-item label="排序" path="sort">
          <n-input-number v-model:value="formData.sort" />
        </n-form-item>
        <n-form-item label="备注" path="note">
          <n-input
            v-model:value="formData.note"
            type="textarea"
            placeholder="请输入备注"
            clearable
          />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script lang="ts" setup>
  import { getDictItemDetail, dictItemAdd, dictItemUpdate } from '@/api/data/dictionary';
  import { onMounted, ref, reactive, nextTick } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';
  import { renderIcon } from '@/utils';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    dictId: {
      type: Number,
      required: true,
      default: 0,
    },
    dictItemId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义参数变量
   */
  const emit = defineEmits(['success', 'update:visible']);
  const formRef = ref();
  const editorRef = ref();
  const message = useMessage();

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: '',
    name: '',
    value: '',
    sort: 0,
    note: '',
  });
  const fwbHeight = document.body.clientHeight - 400;
  const optionsData = ref([]);
  const [modalRegister, { openModal, setProps, setSubLoading }] = useModal({
    title: props.dictItemId ? '编辑字典项' : '新增字典项',
    subBtuText: '确定',
    width: 600,
  });

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.dictItemId
          ? await dictItemUpdate({ ...formData, dictId: props.dictId })
          : await dictItemAdd({ ...formData, dictId: props.dictId });
        setSubLoading(false);
        message.success('操作成功');
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   */
  const setFormData = async () => {
    const data = await getDictItemDetail(props.dictItemId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
    if (formData.options) {
      let arr = formData.options.split(',');
      let kk = [];
      arr.map((item) => {
        let v = item.split('=');
        kk.push({ label: v[1], value: v[0] });
      });
      optionsData.value = kk;
    }
    if (formData.type == 'checkbox' || formData.type == 'selects') {
      if (formData.value) {
        formData.value = formData.value.split(',');
        formData.values = formData.value;
      }
    }
    if (formData.type == 'image') {
      if (formData.value) {
        formData.filePath = formData.value;
      }
    }
    if (formData.type == 'file') {
      if (formData.value) {
        formData.fileName = formData.value.split('|')[0];
        formData.filePath = formData.value.split('|')[1];
      }
    }
    if (formData.type == 'images') {
      formData.valueList.map((item) => {
        formData.fileList.push({
          filePath: item,
        });
      });
    }
    if (formData.type == 'files') {
      formData.valueList.map((item) => {
        let kk = item.split('|');
        formData.fileList.push({
          fileName: kk[0],
          filePath: kk[1],
          name: kk[0],
          url: kk[1],
        });
      });
    }
    if (formData.type == 'ueditor') {
      nextTick(() => {
        editorRef.value.myValue = formData.value;
      });
    }
  };

  /**
   * 添加选项
   */
  const addOptions = () => {
    optionsData.value.push({ label: '', value: '' });
  };

  /**
   * 删除选项
   * @param index 索引
   */
  const delOptions = (index) => {
    optionsData.value.splice(index, 1);
  };

  /**
   * 文件上传
   * @param list 列表
   */
  const fileUploads = (list: any) => {
    formData.fileList = list;
  };

  /**
   * 文件上传
   * @param filePath 文件路径
   * @param fileName 文件名称
   */
  const fileUploadFile = async (filePath: any, fileName: any) => {
    formData.filePath = filePath;
    formData.fileName = fileName;
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    if (props.dictItemId) {
      setFormData();
    }
  });
  //导出方法
  defineExpose({
    openModal,
  });
</script>
