<template>
  <el-dialog
      v-model="props.visible"
      :title="dialogTitle"
      :width="'1350px'"
      :close-on-click-modal="false"
      :before-close="dialogClose"
      style="margin-top:15px;"
  >
    <el-form style="display: flex" ref="formRef" :model="formData" label-width="80px">
      <div style="width: 880px;flex: none" :style="{height:fwbHeight+'px'}">
        <el-form-item label-width="0px" prop="content">
          <Editor ref="editorRef" :height="fwbHeight" name="content"/>
        </el-form-item>
      </div>
      <div style="flex:1;margin-left: 10px">
        <el-form-item
            label="文章标题"
            prop="title"
            :rules="{ required: true,message: '请输入文章标题', trigger: 'blur' }"
        >
          <el-input  placeholder="请输入文章标题" :maxlength="50" v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="categoryId"  :rules="{ required: true, message: '请选择文章分类', trigger: 'change' }">
          <el-tree-select
            v-model="formData.categoryId"
            :data="categoryList"
            :render-after-expand="false"
            :check-strictly="true"
            :props="{ value: 'id',label: 'name'}"
          />
        </el-form-item>
        <el-form-item
            label="文章封面"
            prop="cover"
            :rules="{ required: true,message: '请上传文章封面', trigger: 'change' }"
        >
            <UploadImg @changeFileName="(name)=>formData.coverImgName=name"
                       :fileType=" ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
                       name="article"
                       :fileSize="200"
                       v-model:image-url="formData.cover">
              <template v-slot:tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
            </UploadImg>
        </el-form-item>
        <el-form-item label="导读" prop="intro" :rules="{ required: true, message: '请输入导读', trigger: 'blur' }">
          <el-input  placeholder="请输入" v-model="formData.intro" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="点击率" prop="click" :rules="{ required: true, message: '请输入点击率', trigger: 'blur' }">
          <number-input v-model="formData.click" placeholder="请输入点击率" clearable />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :max="9999"  placeholder="请输入排序"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio v-model="formData.status" :label="0">正常</el-radio>
          <el-radio v-model="formData.status" :label="1">下架</el-radio>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { getCategoryList } from '@/api/content/category';
import { articleAdd,articleUpdate,getArticleDetail } from '@/api/content/article';
import {computed, onMounted,ref,shallowRef,reactive  } from "vue";
import {FormInstance} from "element-plus";
const formRef = shallowRef<FormInstance>();
import UploadImg from "@/components/Upload/Image.vue";
import {useLockFn} from "@/utils/useLockFn";
import Editor from '@/components/Editor/tinymce.vue'
import {message,buildTree} from "@/utils/auth";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  articleId: {
    type: Number,
    required: true,
    default: 0
  },
  searchParamData: {
    type: Object,
    default: {}
  }
});
const categoryList = ref([])
const emit = defineEmits(["success", "update:visible"]);

const dialogTitle = computed(() => {
  return props.articleId ? "编辑内容" : "新增内容";
});

const fwbHeight=document.body.clientHeight -180

const formData = reactive({
  id:"",
  categoryId: "",
  title: "",
  cover:'',
  intro:'',
  content:'',
  status:0,
  click:'',
  sort:0
});

const dialogClose = () => {
  emit("update:visible", false);
};

const setFormData = async (row: any) => {
  const data = await getArticleDetail(props.articleId);
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
    }
  }
  editorRef.value.myValue=formData.content
};

const editorRef=ref()

const handleSubmit = async () => {
  await formRef.value?.validate();
  let ruleForm = JSON.parse(JSON.stringify(formData));
  ruleForm.content=editorRef.value.myValue
  if (!ruleForm.content) {
    message("请添加文章内容","error");
    return;
  }
  props.articleId ? await articleUpdate(ruleForm) : await articleAdd(ruleForm);
  message("操作成功");
  emit("update:visible", false);
  emit("success");
};

const {isLock: subLoading, lockFn: submit} = useLockFn(handleSubmit);
const getAllDict = async () => {
  let list = await getCategoryList();
  categoryList.value = list ? buildTree(list) : [];
};
onMounted(() => {
  getAllDict()
  if(props.articleId){
    setFormData();
  }
});

</script>
