<template>
  <my-layout bg-fff common-shadow>
    <layout-main v-if="article">
      <el-form class="p-15px" :label-width="100" label-position="left" label-suffix="：">
        <el-form-item class="is-required" label="文章标题">
          <el-input v-model="article.title" placeholder="请输入文章标题" :maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="摘要">
          <el-input v-model="article.summary" placeholder="请输入文章摘要" :maxlength="50"></el-input>
        </el-form-item>
        <!-- <el-form-item label="客户标签">
          <el-select v-model="article.tagIds" class="w-full" multiple placeholder="请选择关联客户标签">
            <el-option-group v-for="group in tagGroup" :key="group.value" :label="group.label">
              <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-option-group>
          </el-select>
        </el-form-item> -->
        <el-form-item label="关键字">
          <el-input v-model="article.keyword" placeholder="关键字用于搜索文章使用，每个关键字请用“；”隔开" :maxlength="50"></el-input>
        </el-form-item>
        <!-- <el-form-item label="关联疾病">
          <el-select v-model="disease" :loading="diseaseLoading" class="w-full" remote reserve-keyword
            :remoteMethod="searchDisease" multiple filterable placeholder="请搜索关联疾病">
            <el-option v-for="opt in diseaseList" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item class="is-required" label="文章分类">
          <!-- <el-select v-model="article.cateId" class="w-full" filterable placeholder="请选择文章分类">
            <el-option v-for="opt in cates" :key="opt._id" :label="opt.name" :value="opt._id" />
          </el-select> -->
          <el-cascader v-model="article.cateId" class="w-full" :show-all-levels="false" :options="cateTree"
            :props="{checkStrictly:true,value:'_id'}" clearable />
        </el-form-item>
        <el-form-item label="封面上传">
          <upload-file ref="coverRef" classnames="article-cover" :showFileList="false" listType=""
            @hand-file-change="onHandFileChange" :fileList="fileList" fileType="image/*">
            <el-avatar v-loading="uploadLoading" element-loading-text="正在上传..." shape="square" :size="100" fit="fill"
              :src="cover || article.cover">
              <div w-full h-full flex flex-col justify-center bg-fff items-center>
                <el-button class="w-100px h-100px" type="primary" :icon="Plus" plain>上传封面</el-button>
              </div>
            </el-avatar>
          </upload-file>
        </el-form-item>
        <el-form-item class="is-required" label="文章内容">
          <div class="flex-grow">
            <!-- <el-radio-group v-model="contentType" class="mb-15px">
              <el-radio-button label="link" value="link">链接</el-radio-button>
              <el-radio-button label="content" value="content">自定义内容</el-radio-button>
            </el-radio-group>
            <el-input v-if="contentType === 'link'" v-model="article.link" placeholder="请输入第三方文章链接"></el-input> -->
            <wang-editor v-if="showEditor" v-model="article.content" class="w-full" />
          </div>
        </el-form-item>
      </el-form>
    </layout-main>
    <layout-main v-else :scroll="false">
      <div h-full flex flex-col items-center justify-center>
        <empty-data :title="emptyTxt" />
      </div>
    </layout-main>
    <layout-item v-if="article">
      <div text-center p-15 common-shadow>
        <el-button class="w-100px" @click="cancel()">取消</el-button>
        <el-button class="w-100px" :loading="loading" type="primary" @click="save">保存</el-button>
      </div>
    </layout-item>
  </my-layout>
</template>
<script setup>
import { computed, onActivated, onDeactivated, ref, onMounted } from "vue";
import { watchDebounced } from "@vueuse/core";
import { useRoute, onBeforeRouteUpdate } from "vue-router";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import { file2Base64 } from "@/utils";
import { tagsStore } from "@/store/tags";
import { getArticleCates, getPageDisease, setArticle, getArticle, getArticleCateList } from "@/api/knowledgeBase";
import { updateFile } from "@/api/uploadFIle.js";
import { configStore } from "@/store/config";
const { getGroupTag } = configStore();
const { tags } = storeToRefs(configStore());
import { Plus } from "@element-plus/icons-vue";
import MyLayout, { LayoutMain, LayoutItem } from "@/components/layout";
import uploadFile from "@/components/upload-file/index.vue";
import wangEditor from "@/components/wang-editor/wang-editor";
import EmptyData from "@/components/empty-data.vue";
import { getCateTreeData } from '@/utils/index'

const { removeTag, subTagClosed, unsubTagClosed } = tagsStore();
const tagGroup = computed(() => {
  return tags.value.map((i) => {
    const options = Array.isArray(i.tag) ? i.tag.map((i) => ({ label: i.name, value: i.id })) : [];
    return {
      label: i.groupName,
      value: i.id,
      options: options,
    };
  });
});
const route = useRoute();
let id = "";
const emptyTxt = ref("");
const article = ref({
  cateId: "",
  cover: "",
  tagIds: [],
  disease: [],
  enable: true,
  keyword: "",
  summary: "",
  title: "",
  link: "",
  content: "",
});
const fileList = ref([]);
const coverRef = ref();
const cover = ref("");
const disease = ref([]);
const diseaseList = ref([]);
const loading = ref(false);
const contentType = ref("content");
const diseaseName = ref("");
const diseaseLoading = ref(false);
const showEditor = ref(false);
const cateIdStr = computed(() => {
  if (typeof article.value.cateId === 'string') return article.value.cateId;
  return Array.isArray(article.value.cateId) ? article.value.cateId[article.value.cateId.length - 1] || '' : '';
})

onActivated(async () => {
  if (tags.value.length == 0) await getGroupTag();
  showEditor.value = true;
  getCateList()
  unsubTagClosed(route.fullPath);
  subTagClosed(route.fullPath, reset);
  handleIdChange(route);
});
onDeactivated(() => {
  showEditor.value = false;
});

onBeforeRouteUpdate((to, from, next) => {
  if (from.name === "ARTICLEDETAIL") {
    unsubTagClosed(from.fullPath);
  }
  if (to.name == "ARTICLEDETAIL") {
    subTagClosed(to.fullPath, reset);
    handleIdChange(to);
  }
});


async function getArticleById() {
  const { success, message, data } = await getArticle({ id, corpId: sessionStorage.getItem("corpId") });
  if (success) {
    article.value = data.data;
    if (article.value && article.value.link) {
      contentType.value = "link";
    } else if (article.value && article.value.content) {
      contentType.value = "content";
    }
    disease.value = Array.isArray(article.value.disease)
      ? article.value.disease
        .map((i) => {
          if (typeof i === "string") return i;
          if (typeof i.label === "string") return i.label;
          return "";
        })
        .filter(Boolean)
      : [];
  } else {
    article.value = null;
    emptyTxt.value = message;
  }
}

function reset() {
  id = "";
  cover.value = "";
  article.value = {};
  disease.value = [];
}

function handleIdChange(route) {
  if (route.params.id && route.params.id != id) {
    id = route.params.id;
    getArticleById();
  } else if (id && !route.params.id) {
    id = "";
    article.value = { cateId: history.state.cateId || '' };
  }
  if (!id && history.state.cateId) {
    article.value.cateId = history.state.cateId
  }
}

function searchDisease(str) {
  if (diseaseLoading.value) return;
  diseaseName.value = str.trim();
}

watchDebounced(
  diseaseName,
  async (val) => {
    if (diseaseLoading.value) return;
    diseaseLoading.value = true;
    if (val) {
      const res = await getPageDisease(val, 1, 25);
      const list = res.data && Array.isArray(res.data.list) ? res.data.list.map((i) => ({ label: i.diseaseName, value: i.diseaseName })) : [];
      if (!list.some((i) => i.diseaseName === val)) {
        list.unshift({ label: val, value: val });
      }
      diseaseList.value = list;
    } else {
      diseaseList.value = [];
    }
    diseaseLoading.value = false;
  },
  { debounce: 500 }
);

async function onHandFileChange(e) {
  const data = e.pop();
  coverRef.value && coverRef.value.clearFiles();
  fileList.value = data ? [data.raw] : [];
  cover.value = data && data.raw ? await file2Base64(data.raw) : "";
}

function verify() {
  let message = "";
  if (!article.value.title || article.value.title.trim() === "") {
    message = "请输入文章标题";
  } else if (!cateList.value.some(i => i._id === cateIdStr.value)) {
    message = "请选择文章分类";
  } else if (contentType.value === "link" && !article.value.link) {
    message = "请输入文章的第三方链接";
  } else if (contentType.value === "content" && !article.value.content) {
    message = "请输入文章内容";
  }
  // else if (!validate.isLink(article.value.link.trim())) {
  //   message = '请输入有效的文章链接'
  // }
  message && ElMessage.error(message);
  return !Boolean(message);
}

async function save() {
  if (!verify()) return;
  loading.value = true;
  if (fileList.value[0]) {
    try {
      const res = await updateFile(fileList.value[0].name, fileList.value[0], "article");
      if (res && res.download_url) {
        article.value.cover = res.download_url;
        fileList.value = [];
      } else {
        loading.value = false;
        ElMessage.error("文章封面上传失败");
        return;
      }
    } catch (e) {
      loading.value = false;
      ElMessage.error(e && e.message ? e.message : "文章封面上传失败");
      return;
    }
  }
  const params = {
    ...article.value,
    cateId: cateIdStr.value,
    disease: disease.value,
    corpId: sessionStorage.getItem("corpId"),
    userId: sessionStorage.getItem("userId"),
  };
  if (contentType.value === "link") {
    params.content = "";
  } else params.link = "";
  if (id) params._id = id;
  const { success, message } = await setArticle(params);
  if (success) {
    ElMessage.success(message);
    removeTag(route.fullPath);
    article.value = {};
    reset();
  } else {
    ElMessage.error(message);
  }
  loading.value = false;
}

const cateList = ref([]);
const cateTree = computed(() => getCateTreeData(cateList.value))
async function getCateList() {
  const { success, data, message } = await getArticleCateList(sessionStorage.getItem('corpId'));
  if (success) {
    cateList.value = data && Array.isArray(data.list) ? data.list : []
  } else {
    ElMessage.error(message);
    cateList.value = []
  }
}

function cancel() {
  removeTag(route.fullPath)
  reset()
}

</script>

<style>
.article-cover {
  width: 100px;
  height: 100px;
}
</style>