import { Button, PageHeader } from "ant-design-vue";

import { defineComponent, onMounted, reactive } from "vue";

import loading from "@/components/Provider/Loading";
import { useArticle } from "@/modules";

import { object } from "vue-types";
import WangEditor from "../../components/WangEditor";
import { css } from "@linaria/core";

export default defineComponent({
  props: {
    data: object<CategoryItem>(),
  },
  setup(props) {
    const data: any = props.data || {};
    const artStore = useArticle();
    const state = reactive({
      data: {} as any,
    });

    onMounted(() => {
      initDetail();
    });

    const initDetail = async () => {
      loading.show("");
      artStore.listController.state.query = JSON.stringify({ cid: data._id });
      await artStore.listController.loadPage(1);
      const item = artStore.listController.state.list[0] || {};
      if (item._id) {
        const detRes = await artStore.getArticleDetail(item);
        if (detRes) {
          state.data = detRes;
        }
      }
      loading.hidden();
    };
    const editorChange = ({ html, text }: any) => {
      state.data.content = html;
      state.data.summary = text;
    };
    const submit = () => {
      const subData = { ...state.data };
      if (!subData._id) {
        subData.title = data?.name;
        subData.cid = data._id;
      }
      let summary = state.data.summary.substring(0, 60);
      summary = summary.replace(/\n/g, "");
      subData.summary = summary;
      artStore.addOrUpdateArticle(subData);
    };

    return () => {
      return (
        <div class={Page}>
          <PageHeader title={data?.name}>
            {{
              extra: () => {
                return (
                  <Button type="primary" onClick={submit}>
                    保存
                  </Button>
                );
              },
            }}
          </PageHeader>
          <WangEditor
            key={data._id}
            content={state.data.content}
            onChange={editorChange}
          />
        </div>
      );
    };
  },
});
const Page = css`
  height: 100%;
  display: flex;
  flex-direction: column;
`;
