<!-- @format -->

<template>
  <ns-view-add-form
    ref="nsAddFormRef"
    :schemas="formSchema"
    :model="data"
    :title="uuid ? '编辑文章' : '新增文章'"
    :dataHandle="dataHandle"
    :headActions="headActions"
    :api="formApi" />
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, provide, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import FCKEditor from '/@/view/components/FCKEditor.vue';
  import { http } from '/nerv-lib/util/http';

  export default defineComponent({
    name: 'NewsAdd',
    setup() {
      provide('components', () => {
        return { FCKEditor };
      });
      const router = useRouter();
      const { uuid } = router.currentRoute.value.query;
      const nsAddFormRef = ref();
      const htmlInfo = ref('');
      const imageNetUrl = ref('');
      let uuidList = ref<any>([]);
      const formApi = ref(
        uuid
          ? '/api/content/objs/admin/cms/bg/article/update'
          : '/api/content/objs/admin/cms/bg/article/add',
      );

      const data = ref({
        articleCommonHandleForm: { folderCode: 'mobileArticleManager', content: '', title: '' },
      });

      if (uuid) {
        http.get('/api/content/objs/admin/cms/bg/article/detail', { uuid }).then((res) => {
          console.log(res);
          data.value = res.data.articleCommonVO;
          data.value.tagUuidList = res.data.tagNameList;
          uuidList.value = res.data.tagUuidList;
          data.value.articleCommonHandleForm = {
            folderCode: 'mobileArticleManager',
            folderName: '文章',
            sort: 0,
            title: res.data.articleCommonVO.title,
            content: res.data.articleCommonVO.content,
            articleSource: res.data.articleCommonVO.articleSource,
            imageNetUrl: res.data.articleCommonVO.imageNetUrl,
          };
          data.value.folderCode = 'mobileArticleManager';
          // 编辑->未上架
          data.value.isPublish = 0;
          imageNetUrl.value = res.data.articleCommonVO.imageNetUrl;
          htmlInfo.value = res.data.articleCommonVO.content || '';
        });
      }

      const getTagUuid = async (list = []) => {
        const res = await http.get('/api/content/objs/admin/cms/bg/articleTag/allList', {
          folderCode: 'mobileArticleManager',
        });
        console.log(res);

        const arr = [];
        list?.map((cur) => {
          res.data.some((item) => {
            if (item.tagName == cur) {
              arr.push(item.uuid);
              return true;
            }
          });
        });
        uuidList.value = arr;
      };
      const addTag = (tagName, tagNameList) => {
        http
          .post('/api/content/objs/admin/cms/bg/articleTag/add', {
            folderCode: 'mobileArticleManager',
            tagName,
          })
          .then(() => {
            getTagUuid(tagNameList);
          });
      };
      const dataHandle = (data) => {
        const newData = JSON.parse(JSON.stringify(data));
        newData['articleCommonHandleForm'] = Object.assign(
          newData['articleCommonHandleForm'],
          data,
        );
        newData['tagUuidList'] = uuidList.value;
        return newData;
      };
      const validateResult = computed(() => {
        return !nsAddFormRef.value?.validateResult;
      });
      const headActions = ref({
        actions: [
          {
            label: '发布',
            name: 'NewsDetail',
            dynamicDisabled: validateResult,
            handle: (record, name) => {
              // formApi.value = uuid
              //   ? '/api/content/objs/admin/cms/bg/article/publish'
              //   : '/api/content/objs/admin/cms/bg/article/add';
              data.value.isPublish = 1;
              nsAddFormRef.value?.submit();
            },
          },
        ],
      });

      const formSchema = ref([
        {
          field: 'folderCode',
          defaultValue: 'mobileArticleManager',
        },
        {
          field: 'articleCommonHandleForm',
          defaultValue: { folderCode: 'mobileArticleManager', folderName: '文章', sort: 0 },
        },
        {
          field: 'uuid',
          defaultValue: uuid,
        },
        {
          field: 'isPublish',
          defaultValue: 0,
        },
        {
          field: 'title',
          label: '文章标题',
          component: 'NsInput',

          componentProps: {
            placeholder: '请输入',
            // 禁止输入
            // disabled: true,
            // onChange: (e) => {
            //   data.value.articleCommonHandleForm['title'] = e.target.value;
            // },
          },
          rules: [
            {
              required: true,
              message: '请输入文章标题',
            },
          ],
        },
        {
          field: 'articleSource',
          label: '消息来源',
          component: 'NsInput',
          componentProps: {
            placeholder: '请输入',
            // onChange: (e) => {
            //   data.value.articleCommonHandleForm['articleSource'] = e.target.value;
            // },
          },
          rules: [
            {
              required: true,
              message: '请输入消息来源',
            },
          ],
        },
        {
          field: 'tagUuidList',
          label: '文章标签',
          component: 'nsSelectApi',
          componentProps: {
            mode: 'tags',
            api: '/api/content/objs/admin/cms/bg/articleTag/allList',
            params: { folderCode: 'mobileArticleManager' },
            autoSelectFirst: false,
            resultField: 'data',
            labelField: 'tagName',
            valueField: 'tagName',
            immediate: true,
            dropdownReload: true,
            placeholder: '请选择',
            filterOption: (input, option) => {
              return option.tagName?.indexOf(input) >= 0;
            },
            // onChange: (a, b) => {
            //   console.log(a, b, 'onchange');
            //   // getTagUuid(a);
            // },
            onSelect: (a, b) => {
              if (JSON.stringify(b) == '{}') {
                addTag(a, data.value.tagUuidList);
                // console.log(data.value);
              } else {
                getTagUuid(data.value.tagUuidList);
              }
              console.log(a, JSON.stringify(b), 'onselect');
            },
          },
          // rules: [
          //   {
          //     required: true,
          //     message: '请选择',
          //     type: 'array',
          //   },
          // ],
        },

        {
          field: 'imageNetUrl',
          component: 'NsUpload',
          label: '文章图片',
          componentProps: {
            // 上传的地址
            url: '/api/fileunify/objs/admin/MaterialFile',
            // 上传的图片大小
            maxSize: 5242880,
            // 上传的图片类型
            fileType: ['jpg', 'png', 'jpeg'],
            // 展示图片数量
            count: 1,
            // 上传的文件类型，0-证书，1-图片，2-身份证件
            uploadType: 1,
            params: {
              groupCode: 'mobile_img',
            },
            baseImageUrl: imageNetUrl,
            // onChange: (e) => {
            //   data.value.articleCommonHandleForm['imageNetUrl'] = e;
            // },
          },
        },
        {
          field: 'content',
          component: 'FCKEditor',
          class: 'ns-form-item-full ns-form-item-padding ns-richText-ZIndex',
          label: '文章内容',
          componentProps: {
            htmlInfo: htmlInfo,
            // onChange: (a) => {
            //   data.value.articleCommonHandleForm['content'] = a;
            // },
          },
          rules: [
            {
              required: true,
              message: '内容不能为空',
              trigger: 'blur',
            },
          ],
        },
      ]);

      return {
        formSchema,
        data,
        headActions,
        nsAddFormRef,
        dataHandle,
        uuid,
        formApi,
      };
    },
  });
</script>
