<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    okText="立刻发布"
    width="60%"
    min-width="600px"
    :height="550"
    :showOkBtn="!isView"
    @ok="handleOk"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="modelRef" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  // computed
  import { defineComponent, h, 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 { dateUtil, formatToDateTime } from '/@/utils/dateUtil';
  import { TableImg } from '/@/components/Table';

  const { t } = useI18n();
  const now = dateUtil();

  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: {
            maxlength: 10,
            showCount: true,
          },
          colProps: {
            span: 22,
          },
        },
        {
          field: 'selectTime',
          component: 'RangePicker',
          componentProps: {
            format: 'YYYY-MM-DD HH:mm',
            showTime: true,
            disabledDate(current) {
              return current && current < now;
            },
            disabledTime(_) {
              // if (type === 'start') {
              //   return {
              //     // ...Array(dateUtil().minute()).keys()
              //     disabledHours: () => [...Array(dateUtil().hour()).keys()],
              //     disabledMinutes: () => [],
              //     disabledSeconds: () => [],
              //   };
              // }
              return {
                disabledHours: () => [...Array(dateUtil().hour()).keys()],
                disabledMinutes: () => [],
                disabledSeconds: () => [],
              };
            },
          },
          label: '时间段',
          required: true,

          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject('请选择时间段');
                }
                // console.log('check', rule, value, record);
                // // console.log('value[1]', value[1].unix());
                if (value[0].unix() > value[1].unix()) {
                  return Promise.reject('开始时间要小于结束时间');
                }
                if (value[0].unix() > value[1].unix() - 300) {
                  return Promise.reject('时间段最小5分钟');
                }
                return Promise.resolve();
              },

              trigger: 'change',
            },
          ],
          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: '内容',
          required: true,
          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,
          helpMessage: '支持png，jpg和gif格式的图片，建议分辨率为200*400，最大为5MB',
          itemProps: {
            validateTrigger: 'blur',
          },
          ifShow: ({ model }) => {
            return model['type'] === 1 && !isView.value;
          },
          componentProps: {
            api: uploadApi,
            maxSize: 5,
            emptyHidePreview: true,
            maxNumber: 1,
            accept: ['jpg', 'jpeg', 'gif', 'png'],
            helpText: '支持png，jpg和gif格式的图片，建议分辨率为200*400，最大为5MB',
            afterFetch: function (data) {
              Reflect.set(data, 'url', data.message.url);
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
        {
          field: 'content2Image',
          component: 'Input',
          required: true,
          ifShow: ({ model }) => {
            return model['type'] === 1 && isView.value;
          },
          render: ({ model, field }) => {
            return h(TableImg, {
              imgList: [model[field]],
              size: 160,
              style: {
                height: 160,
              },
            });
          },
          label: '内容',
          colProps: {
            span: 10,
          },
        },
      ];
      const title = ref('创新消息');
      const { createMessage } = useMessage();
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        fieldMapToTime: [
          // 支持多个字段
          ['selectTime', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm'],
        ],
        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,
          });
          if (data.startTime && data.endTime) {
            setFieldsValue({
              selectTime: [formatToDateTime(data.startTime), formatToDateTime(data.endTime)],
            });
          }
          if (data.type === 0) {
            setFieldsValue({
              content1: data.content,
            });
          }
          if (data.type === 1) {
            setFieldsValue({
              content2: [data.content],
              content2Image: [data.content],
            });
          }
          updateSchemas = schemas.map((item: FormSchema) => {
            item.componentProps = {
              ...item.componentProps,
              disabled: true,
            };
            return item;
          });
        } else {
          title.value = '创建消息';
        }
        await updateSchema(updateSchemas);
      }

      async function handleOk() {
        let data = await validate();
        if (
          data.selectTime[0].valueOf() < dateUtil().valueOf() ||
          data.selectTime[1].valueOf() < dateUtil().valueOf()
        ) {
          createMessage.warn('开始或结束时间不能少于当前时间');
          return;
        }
        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: [
            formatToDateTime(data.selectTime[0]),
            formatToDateTime(data.selectTime[1]),
          ],
          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>
