<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="code"
          :rule="{ required: true, message: '请输入配置项编码', trigger: 'blur' }"
        >
          <n-input
            class="ls-input"
            v-model:value="formData.code"
            placeholder="请输入配置项编码"
            clearable
          />
        </n-form-item>
        <n-form-item
          label="配置项类型"
          path="type"
          class="flex-1"
          :rule="{ required: true, message: '请选择配置项类型', trigger: 'change' }"
        >
          <n-select
            v-model:value="formData.type"
            class="flex-1"
            clearable
            placeholder="请选择配置项类型"
            :on-update:value="handleTypeChange"
            :options="typeList"
          />
        </n-form-item>
        <n-form-item label="配置项源" path="options">
          <div>
            <n-icon size="25" color="#165dff" style="cursor: pointer" @click="addOptions">
              <plusCircleOutlined />
            </n-icon>
            <div v-for="(item, index) in optionsData" :key="index" style="margin-top: 8px">
              <div class="flex item-center">
                <n-input v-model:value="item.label" placeholder="请输入name" clearable />
                <div style="margin: 0 10px">-</div>
                <n-input v-model:value="item.value" placeholder="请输入value" clearable />
                <n-icon
                  size="25"
                  color="#f56c6c"
                  style="cursor: pointer; margin-left: 10px"
                  @click="delOptions(index)"
                >
                  <MinusCircleOutlined />
                </n-icon>
              </div>
            </div>
          </div>
        </n-form-item>
        <n-form-item label="配置项值" path="value">
          <template
            v-if="
              formData.type == 'text' ||
              formData.type == 'readonly' ||
              formData.type == 'textarea' ||
              formData.type == 'password'
            "
          >
            <n-input
              v-model="formData.value"
              :type="
                formData.type == 'textarea'
                  ? 'textarea'
                  : formData.type == 'password'
                  ? 'password'
                  : ''
              "
              placeholder="请输入配置项值"
              clearable
            />
          </template>
          <template v-else-if="formData.type == 'number'">
            <number-input v-model="formData.value" placeholder="请输入配置项值" />
          </template>
          <template v-else-if="formData.type == 'icon'">
            <icon-picker v-model:icon="formData.value">
              <template #iconSelect>
                <n-input v-model:value="formData.value" placeholder="请选择菜单图标">
                  <template #prefix>
                    <component :is="iconComponent(formData.value)" />
                  </template>
                </n-input>
              </template>
            </icon-picker>
          </template>
          <template v-else-if="formData.type == 'radio'">
            <n-radio-group v-model:value="formData.value">
              <n-radio v-for="(item, index) in optionsData" :value="item.value" :key="index">
                {{ item.label }}
              </n-radio>
            </n-radio-group>
          </template>
          <template v-else-if="formData.type == 'checkbox'">
            <n-checkbox-group v-model:value="formData.values">
              <n-checkbox :value="item.value" :key="index" v-for="(item, index) in optionsData">{{
                item.label
              }}</n-checkbox>
            </n-checkbox-group>
          </template>
          <template v-else-if="formData.type == 'select'">
            <n-select v-model:value="formData.value" :options="optionsData" />
          </template>
          <template v-else-if="formData.type == 'selects'">
            <n-select v-model:value="formData.values" mode="multiple" :options="optionsData" />
          </template>
          <template v-else-if="formData.type == 'date' || formData.type == 'datetime'">
            <n-date-picker
              :type="formData.type"
              placeholder="请选择日期"
              v-model:value="formData.value"
              style="width: 100%"
              :value-format="formData.type == 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss'"
              :format="formData.type == 'date' ? 'yyyy-MM-dd' : 'yyyy-MM-dd HH:mm:ss'"
            />
          </template>
          <template v-else-if="formData.type == 'image'">
            <UploadImg
              @change-file-name="(name) => (formData.fileName = name)"
              :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
              name="config"
              :fileSize="200"
              v-model:image-url="formData.filePath"
            >
              <template #tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
            </UploadImg>
          </template>
          <template v-else-if="formData.type == 'images'">
            <UploadImgs
              @upload="fileUploads"
              file-type=".jpeg,.png,.jpg,.gif"
              name="config"
              :fileSize="200"
              :multiple="true"
              :fileLists="formData.fileList"
            />
          </template>
          <template v-else-if="formData.type == 'file'">
            <UploadFile
              @upload="fileUploadFile"
              file-type=".xlsx.xls.doc.docx"
              name="config"
              :fileLists="
                formData.filePath ? [{ name: formData.fileName, url: formData.filePath }] : []
              "
            />
          </template>
          <template v-else-if="formData.type == 'files'">
            <UploadFile
              @upload="fileUploads"
              file-type=".xlsx.xls.doc.docx"
              name="config"
              :multiple="true"
              :fileLists="formData.fileList"
            />
          </template>
          <template v-else-if="formData.type == 'ueditor'">
            <Editor ref="editorRef" :height="fwbHeight" class="flex-1" name="config" />
          </template>
        </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="status">
          <n-radio-group v-model:value="formData.status" name="status">
            <n-radio :value="1">正常</n-radio>
            <n-radio :value="2">停用</n-radio>
          </n-radio-group>
        </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 { getConfigItemDetail, configItemAdd, configItemUpdate } from '@/api/data/config';
  import { onMounted, ref, reactive, nextTick } from 'vue';
  import { useMessage } from 'naive-ui';
  import { PlusCircleOutlined, MinusCircleOutlined } from '@vicons/antd';
  import { useModal } from '@/components/Modal';
  import Editor from '@/components/Editor/tinymce.vue';
  import UploadImg from '@/components/Upload/Image.vue';
  import UploadImgs from '@/components/Upload/Images.vue';
  import UploadFile from '@/components/Upload/file.vue';
  import IconPicker from '@/components/icon/picker.vue';
  import * as VueIcon from '@vicons/antd';
  import { renderIcon } from '@/utils';

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    configId: {
      type: Number,
      required: true,
      default: 0,
    },
    configItemId: {
      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: '',
    code: '',
    value: '',
    values: [],
    fileName: '',
    filePath: '',
    fileList: [],
    valueList: [],
    sort: 0,
    options: '',
    type: 'text',
    status: 1,
    note: '',
  });
  const fwbHeight = document.body.clientHeight - 400;
  const optionsData = ref([]);
  const [modalRegister, { openModal, setProps, setSubLoading }] = useModal({
    title: props.configItemId ? '编辑配置项' : '新增配置项',
    subBtuText: '确定',
    width: 600,
  });
  /**
   * 定义类型数据
   */
  const typeList = ref([
    {
      label: '隐藏',
      value: 'hidden',
    },
    {
      label: '只读文本',
      value: 'readonly',
    },
    {
      label: '数字',
      value: 'number',
    },
    {
      label: '单行文本',
      value: 'text',
    },
    {
      label: '多行文本',
      value: 'textarea',
    },
    {
      label: '密码',
      value: 'password',
    },
    {
      label: '单选框',
      value: 'radio',
    },
    {
      label: '复选框',
      value: 'checkbox',
    },
    {
      label: '下拉框(单选)',
      value: 'select',
    },
    {
      label: '下拉框(多选)',
      value: 'selects',
    },
    {
      label: '字体图标',
      value: 'icon',
    },
    {
      label: '日期',
      value: 'date',
    },
    {
      label: '时间',
      value: 'datetime',
    },
    {
      label: '单张图片',
      value: 'image',
    },
    {
      label: '多张图片',
      value: 'images',
    },
    {
      label: '单个文件',
      value: 'file',
    },
    {
      label: '多个文件',
      value: 'files',
    },
    {
      label: '富文本编辑器',
      value: 'ueditor',
    },
  ]);

  /**
   * 定义Icon组件
   * @param icon 图标
   */
  const iconComponent = (icon) => {
    const IconComponent = renderIcon(VueIcon[icon]);
    return IconComponent;
  };
  /**
   * 执行类型选择发生变化
   */
  const handleTypeChange = (e) => {
    formData.type = e;
    formData.fileList = [];
    formData.fileName = '';
    formData.filePath = '';
    formData.values = [];
    formData.value = '';
    if (e == 'ueditor') {
      setProps({ width: 800 });
    } else {
      setProps({ width: 600 });
    }
    if (e == 'date' || e == 'datetime') {
      formData.value = null;
    }
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        formData.options = '';
        optionsData.value.map((item, index) => {
          formData.options += `${item.value}=${item.label}${
            index < optionsData.value.length - 1 ? ',' : ''
          }`;
        });

        if (formData.type == 'checkbox' || formData.type == 'selects') {
          formData.value = formData.values.join(',');
        }
        if (formData.type == 'image') {
          formData.value = formData.filePath;
        }
        if (formData.type == 'file') {
          formData.value = formData.fileName + '|' + formData.filePath;
        }
        if (formData.type == 'images') {
          formData.value = '';
          formData.fileList.map((item, index) => {
            formData.value += `${item.filePath}${index < formData.fileList.length - 1 ? ',' : ''}`;
          });
        }
        if (formData.type == 'files') {
          formData.value = '';
          formData.fileList.map((item, index) => {
            formData.value += `${item.fileName}|${item.filePath}${
              index < formData.fileList.length - 1 ? ',' : ''
            }`;
          });
        }
        if (formData.type == 'ueditor') {
          formData.value = editorRef.value.myValue;
        }
        props.configItemId
          ? await configItemUpdate({ ...formData, configId: props.configId })
          : await configItemAdd({ ...formData, configId: props.configId });
        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 getConfigItemDetail(props.configItemId);
    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.configItemId) {
      setFormData();
    }
  });
  //导出方法
  defineExpose({
    openModal,
  });
</script>
