<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    :width="1000"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" >
        <template #text="{ model, field }">
          {{ model[field]  }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadApi } from '/@/api/product/index';
  import { newAddNews, NewsDetail, newUpdateNews } from '/@/api/operate'
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Tinymce } from '/@/components/Tinymce/index';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const title = ref('新增新闻');
      const fileFlow = reactive({
        coverImageUrl:''
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          show:false,
          label: 'id',
          required: false,
        },{
          field: 'language',
          component: 'Input',
          show:false,
          label: 'language',
          defaultValue:'cn',
          required: false,
        },{
            field: 'title',
            component: 'Input',
            required: true,
            label: '新闻标题',
            componentProps: {
              maxlength: 50,
            },
            colProps: {
              span: 22,
            },
        },{
            field: 'source',
            component: 'Input',
            label: '新闻来源',
            required: true,
            componentProps: {
              maxlength: 15,
            },
            colProps: {
              span: 22,
            },
        },
        {
          field: 'coverImageUrl',
          component: 'Upload',
          label: '封面',
          required: true,
          rules: [{ required: true, message: t('common.uploadMessge') }],
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            maxSize: 1,
            accept: ['jpg'],
            afterFetch: function (data) {
              console.log('uploadApi',data)
              fileFlow.coverImageUrl = data.url
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
        {
          field: 'newType',
          label: '类型',
          component: 'RadioButtonGroup',
          required: true,
          defaultValue: 2,
          componentProps: {
            onChange: NewTypeChange,
            options: [
              { label: '链接', value: 1 },
              { label: '图文', value: 2 },
            ],
          },
        },{
            field: 'newsUrl',
            component: 'Input',
            label: '新闻链接',
            ifShow:false,
            required: true,
            colProps: {
              span: 22,
            },
            componentProps: {
              maxlength: 200,
            },
        },
        {
          field: 'content',
          label: '新闻内容',
          component: 'Input',
          required: true,
          colProps: {
            span: 22,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject('请输入新闻内容');
                }
                if (formatrichtext(value) > 10000) {
                  /* eslint-disable-next-line */
                  return Promise.reject('新闻内容不能超过10000');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          render: ({ model, field }) => {
            return h(Tinymce, {
              value: model[field],
              maxlength: 10000,
              onChange: (value: string) => {
                model[field] = value;
              },
              showImageUpload: true,
            });
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      const formatrichtext = (richtext, len = 0) => {
          let content = richtext.replace(/<[^>]+>/g,"");    
          content = richtext.replace(/<.+?>/g, '');  
          content = content.replace(/ /ig, ''); /* 去除  */    ;
          // content = content.replace(/&nbsp/ig, ''); /* 去除  */   
          content = content.replace(/\s/ig, ''); /* 去除空格 */
          console.log('formatrichtext',content && content.length)
          return content && content.length;
      }
      async function onDataReceive(data) {
        modelRef.value = data
        resetFields();
        NewTypeChange(data.newType)
        if(data.id){
          title.value = '编辑新闻'
          const detail = await NewsDetail({id:data.id})
          setFieldsValue({
            ...detail,
            newsUrl:detail.newType == 1?detail.content:'',
            content:detail.newType != 1?detail.content:'',
            coverImageUrl:detail.coverImageUrl?[detail.coverImageUrl]:''
          });
        }else{
          title.value = '新增新闻'
          setFieldsValue({
            content:'',
            ...data,
            newType:2,
          });
        }
      }
      function NewTypeChange(val = 2){
        console.log('NewTypeChange',val)
        updateSchema([
          { field: 'content', ifShow:val == 2,},
          { field: 'newsUrl', ifShow:val != 2,},
        ])
      } 
      const handleSubmit = async () => {
        const params = await validate();
        let apiUrl = title.value == '新增新闻'?newAddNews:newUpdateNews
        console.log('validate',params)
        const apiData = {
          ...params as any,
          coverImageUrl:params.coverImageUrl && params.coverImageUrl[0],
          content:params.newType == 1?params.newsUrl:params.content
        }
        try {
          await apiUrl(apiData);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        NewTypeChange,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        title,
        t,
      };
    },
  });
</script>
