<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    width="60%"
    min-width="600px"
    @ok="handleOk"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="modelRef" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  // computed
  import { defineComponent, ref } from 'vue';

  import { addNoticeApi, editNoticeApi } from '/@/api/notification/list';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  // import { ListAllCompanyApi } from '/@/api/corporation/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  // import { useUserStore } from '/@/store/modules/user';
  // import { Tinymce } from '/@/components/Tinymce';
  import { uploadApi } from '/@/api/advertisement/list';
  import { formatToDateTime } from '/@/utils/dateUtil';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'ok', 'cancel'],
    setup(_, { emit }) {
      const modelRef = ref({});
      const isView = ref(false);
      // const userStore = useUserStore();
      // const { getCheckRole } = userStore;
      // const userinfo = computed(() => userStore.getUserInfo);
      // const { companyId } = userinfo.value;

      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },

        {
          field: 'title',
          component: 'Input',
          label: '标题',
          required: true,
          componentProps: {},
          colProps: {
            span: 22,
          },
        },

        {
          field: 'effectiveTime',
          component: 'RangePicker',
          componentProps: {
            format: 'YYYY-MM-DD HH:mm:ss',
            showTime: true,
          },
          label: '时间段',
          required: true,
          colProps: {
            span: 22,
          },
        },
        {
          field: 'type',
          component: 'RadioButtonGroup',
          label: '类型',
          required: true,
          colProps: {
            span: 22,
          },
          defaultValue: 0,
          componentProps: {
            options: [
              { label: '文字', value: 0 },
              { label: '图片', value: 1 },
            ],
          },
        },
        {
          field: 'content1',
          label: '内容',
          component: 'InputTextArea',
          ifShow: ({ model }) => {
            return model['type'] === 0;
          },
          colProps: {
            span: 22,
          },
          componentProps: {
            showCount: true,
            maxlength: 200,
            autoSize: {
              minRows: 6,
            },
          },
        },
        {
          field: 'content2',
          label: '内容',
          component: 'Upload',
          required: true,
          itemProps: {
            validateTrigger: 'blur',
          },
          ifShow: ({ model }) => {
            return model['type'] === 1;
          },
          componentProps: {
            api: uploadApi,
            maxSize: 5,
            emptyHidePreview: true,
            maxNumber: 1,
            accept: ['jpg', 'jpeg', 'gif', 'png'],
            afterFetch: function (data) {
              Reflect.set(data, 'url', data.message.url);
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
      ];
      const title = ref('新 增');
      const { createMessage } = useMessage();
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      // closeModal
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      async function onDataReceive(data) {
        console.log('onDataReceive', data);
        // 方式1;
        resetFields();
        isView.value = false;
        let updateSchemas = schemas.map((item: FormSchema) => {
          item.componentProps = {
            ...item.componentProps,
            disabled: false,
          };
          return item;
        });
        if (data.isView) {
          isView.value = true;
          title.value = '查看';
          setFieldsValue({
            ...data,
            effectiveTime: [data.startTime, data.endTime],
          });
          if (data.type === 0) {
            setFieldsValue({
              content1: data.content,
            });
          }
          if (data.type === 1) {
            setFieldsValue({
              content2: [data.content],
            });
          }
          updateSchemas = schemas.map((item: FormSchema) => {
            item.componentProps = {
              ...item.componentProps,
              disabled: true,
            };
            return item;
          });
        }
        await updateSchema(updateSchemas);
      }

      async function handleOk() {
        let data = await validate();
        console.log('data', data);

        const requestApi = data.id ? editNoticeApi : addNoticeApi;
        let res = await requestApi({
          title: data.title,
          content: data.type === 0 ? data.content1 : data.content2[0],
          type: String(data.type),
          effectiveTime: data.effectiveTime.map((i) => formatToDateTime(i)),
          id: data.id,
        });
        console.log('res', res);
        emit('ok', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }

      return {
        register,
        title,
        schemas,
        registerForm,
        modelRef,
        handleOk,
        resetFields,
        isView,
      };
    },
  });
</script>
