<template>

  <!-- 主体部分 -->
  <div class="xl:w-screen-xl m-auto py-4 mt-12 px-4 sm:px-0 sm:mt-20">
    <el-page-header :icon="ArrowLeft" @back="goBack">
      <template #content>
        <span class="text-large font-600 line-clamp-1"> 发布文章 </span>
      </template>

      <div class="my-5 sm:my-10">
        <el-form :model="form" label-width="auto" size="large">
          <el-form-item label-position="left" label-width="0">
            <el-input v-model="form.title" placeholder="文章标题"/>
          </el-form-item>
          <el-form-item label-position="left" label-width="0">
            <!-- 编辑器 -->
            <MdEditor v-model="form.content" @onUploadImg="onUploadImg"/>
          </el-form-item>
          <el-form-item label="关联栏目" label-position="left">
            <el-switch v-model="hasCategory" />
            <div v-if="hasCategory" class="mx-5">
              <el-cascader v-model="category" :options="categoryList" placeholder="选项关联的栏目" @change="handleCategory" />
            </div>
          </el-form-item>
          <el-form-item label="选择话题" label-position="left">
            <div class="w-lg">
              <el-select
                v-model="topic"
                multiple
                placeholder="选择话题"
              >
                <el-option
                  v-for="item in topicList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label-position="left" label-width="0">
            <div class="m-auto text-center flex justify-center text-center items-center">
              <el-button size="large" @click="saveDraft">存草稿</el-button>
              <el-button class="sm:w-auto w-full" size="large" type="primary" @click="onRelease">发布</el-button>
            </div>
          </el-form-item>


          <div class="flex flex-col">
            <el-form-item class="my-4" label-position="left">

            </el-form-item>
          </div>
        </el-form>
      </div>

    </el-page-header>
  </div>

</template>
<script lang="ts" setup>
import {ArrowLeft, Search, EditPen} from '@element-plus/icons-vue'
import type {CmsArticle, CmsArticleParam} from "~/api/cms/cmsArticle/model";
import dayjs from "dayjs";
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import type {CmsWebsite, CmsWebsiteParam} from "~/api/cms/cmsWebsite/model";
import {addCmsArticle, pageCmsArticle, updateCmsArticle} from "~/api/cms/cmsArticle";
import type {UploadUserFile} from 'element-plus'
import useFormData from "~/utils/use-form-data";
import {uploadOss} from "~/api/system/file";
import {updateCmsWebsiteAll} from "~/api/cms/cmsWebsite";
import {addShopMerchantApply, updateShopMerchantApply} from "~/api/shop/shopMerchantApply";
import type {CmsNavigation} from "~/api/cms/cmsNavigation/model";
import {listDictData} from "~/api/system/dict-data";
import {getLang} from "~/utils/common";

const route = useRoute();
const router = useRouter();
// 页面信息
const list = ref<CmsArticle[]>([]);
const total = ref(0);
const id = ref<number>();
const hasCategory = ref<boolean>(false);
const files = ref<UploadUserFile[]>([])
const isUpdate = ref<boolean>(false);
const categoryList = ref<CmsNavigation[]>([])
const category = ref<any>()
const topic = ref<string>()
const topicList = ref<any[]>()
const srcList = ref<string[]>([])
const inputWidth = ref<string>('180px');
const showSearch = ref<boolean>(false);
const loading = ref(false)

// 搜索表单
const where = reactive<CmsWebsiteParam>({
  keywords: '',
  page: 1,
  limit: 12,
  status: undefined,
  recommend: undefined,
  search: true,
  websiteType: undefined,
  categoryId: undefined,
  lang: undefined
});


// 配置信息
const {form, assignFields} = useFormData<CmsArticle>({
  // 文章id
  articleId: undefined,
  // 文章模型
  model: undefined,
  // 文章标题
  title: undefined,
  // 分类类型
  type: undefined,
  // 展现方式
  showType: undefined,
  // 文章类型
  categoryId: 4094,
  // 文章分类
  categoryName: undefined,
  parentId: undefined,
  // 封面图
  image: undefined,
  // 附件
  files: undefined,
  // 附件
  fileList: [],
  // 缩列图
  thumbnail: undefined,
  // 视频地址
  video: undefined,
  // 上传的文件类型
  accept: undefined,
  // 来源
  source: undefined,
  // 标签
  tags: undefined,
  // 文章内容
  content: undefined,
  // 文章编辑器
  editor: 2,
  // 多语言
  lang: getLang(),
  // 虚拟阅读量
  virtualViews: undefined,
  // 实际阅读量
  actualViews: undefined,
  // 访问权限
  permission: 0,
  // 访问密码
  password: undefined,
  password2: undefined,
  // 用户ID
  userId: undefined,
  // 用户昵称
  nickname: undefined,
  // 账号
  username: undefined,
  // 用户头像
  // userAvatar: undefined,
  author: undefined,
  // 所属门店ID
  shopId: undefined,
  //
  likes: undefined,
  // 排序
  sortNumber: undefined,
  // 备注
  comments: undefined,
  // 状态
  status: undefined,
  // 创建时间
  createTime: undefined,
  // 更新时间
  updateTime: undefined,
  // 租户ID
  tenantId: undefined,
  // 租户名称
  tenantName: undefined,
  // 租户logo
  logo: undefined,
  // 详情页路径
  detail: undefined
});

const goBack = () => {
  router.back();
}

const handleCategory = () => {

}
const handleFocus = () => {
  inputWidth.value = '400px'; // 聚焦时宽度
}
const handleBlur = () => {
  inputWidth.value = '180px'; // 聚焦时宽度
}

const showDomain = (item: CmsWebsite) => {
  id.value = Number(item.websiteId);
};

const hideDomain = () => {
  id.value = 0;
};

// 加载页面数据
const reload = async () => {
  // 字典Topics
  listDictData({dictCode: 'Topics'}).then(data => {
    topicList.value = data;
  })
  listDictData({dictCode: 'AskColumn'}).then(data => {
    categoryList.value = data;
  })
  await pageCmsArticle({
    ...where,
    model: 'ask'
  }).then(response => {
    if (response?.list) {
      list.value = response?.list;
      total.value = response.count;
    }
  }).catch(() => {
  }).finally(() => showSearch.value = false)
}

/**
 * 搜索
 * @param data
 */
const search = (data: CmsArticleParam) => {
  where.page = data.page;
  reload();
}

// 图片上传
const onUploadImg = async (files: any, callback: any) => {
  const res = await Promise.all(
    files.map((file: any) => {
      return new Promise((rev, rej) => {
        const form = new FormData();
        form.append('file', file);
        uploadOss(file).then((res: any) => rev(res))
          .catch((error: any) => rej(error));
      });
    })
  );
  callback(res.map((item) => item.url));
};

const saveDraft = () => {

}

const onRelease = () => {
  if (loading.value) return // 防止重复提交

  form.files = undefined;
  if (srcList.value.length > 0) {
    form.files = JSON.stringify(srcList.value)
  }
  // if(!form.developer){
  //   form.developer = developer.value;
  // }

  loading.value = true
  const saveOrUpdate = isUpdate.value ? updateCmsArticle : addCmsArticle;
  saveOrUpdate(form).then(() => {
    ElMessage.success('发布成功');
  });

}

watch(
  () => route.query.id,
  (id) => {
    if (id) {
      isUpdate.value = true;
    }
    reload();
  },
  {immediate: true}
);
</script>
<style lang="scss">
.el-input {
  transition: width 0.3s ease;
}
</style>


