<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    :width="800"
    @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 { caseaddOrUpdateApi } 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: 'subTitle',
        component: 'InputTextArea',
        required: true,
        label: '摘要',
        componentProps: {
          maxLength: 500,
          rows: 4,
          placeholder: '请输入摘要',
        },
        colProps: {
          span: 22,
        },
      },
      {
        field: 'typeId',
        component: 'Select',
        required: true,
        label: '类型',
        componentProps: {
          placeholder: '请选择类型',
          options: [
            {
              label: '智慧城市',
              value: 'smartCity',
              key: 'smartCity',
            },
            {
              label: '博物馆',
              value: 'museum',
              key: 'museum',
            },
            {
              label: '刑侦消防',
              value: 'government',
              key: 'government',
            },
            {
              label: '房产营销',
              value: 'property',
              key: 'property',
            },
          ],
        },
        colProps: {
          span: 12,
        },
      },
      {
        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', 'jpeg', 'png'],
          afterFetch: function (data) {
            console.log('uploadApi', data);
            fileFlow.coverImageUrl = data.url;
            return data;
          },
        },

        colProps: {
          span: 22,
        },
      },
      {
        field: 'logo',
        component: 'Upload',
        label: 'LOGO',
        required: true,
        rules: [{ required: true, message: t('common.uploadMessge') }],
        // helpMessage: t('routes.corporation.uploadHelp'),
        itemProps: {
          validateTrigger: 'blur',
        },
        componentProps: {
          api: uploadApi,
          maxNumber: 1,
          maxSize: 1,
          accept: ['jpg', 'jpeg', 'png'],
          afterFetch: function (data) {
            console.log('uploadApi', data);
            fileFlow.coverImageUrl = data.url;
            return data;
          },
        },

        colProps: {
          span: 22,
        },
      },
      {
        field: 'iconIdList',
        component: 'Select',
        required: true,
        label: '图标',
        componentProps: {
          placeholder: '请选择icon图标',
          mode:'multiple',
          options: [
            {
              label: '四维看看',
              value: 1,
              key: '1',
            },
            {
              label: '四维看见',
              value: 2,
              key: '2',
            },
            {
              label: '四维深时',
              value: 3,
              key: '3',
            },
            {
              label: '无人机航拍',
              value: 11,
              key: '11',
            },
            {
              label: '四维时代',
              value: 5,
              key: '5',
            },
          ],
        },
        colProps: {
          span: 22,
        },
      },{
        field: 'sort',
        component: 'InputNumber',
        label: '排序',
        required: true,
        componentProps: {
          min:1,
        },
        colProps: {
          span: 22,
        },
      },{
          field: 'detailContent',
          label: '正文',
          component: 'Input',
          required: true,
          colProps: {
            span: 22,
          },
          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);
    });
    async function onDataReceive(data) {
      modelRef.value = data;
      // resetFields();
      // if (data.newType) {
      //   NewTypeChange(data.newType);
      // }
      if (data.id) {
        title.value = '编辑案例';
        const detail = data;
        console.log('detail',detail,detail.iconIds && JSON.parse(detail.iconIds))
        setFieldsValue({
          ...detail,
          iconIdList:detail.iconIds && JSON.parse(detail.iconIds),
          newsUrl: detail.newType == 1 ? detail.detailContent : '',
          detailContent: detail.newType != 1 ? detail.detailContent : '',
          coverImageUrl: detail.coverImageUrl ? [detail.coverImageUrl] : '',
          logo: detail.logo ? [detail.logo] : '',
        });
      } else {
        title.value = '新增案例';
        setFieldsValue({
          detailContent: '',
          ...data,
        });
      }

    }
    function NewTypeChange(val) {
      console.log('NewTypeChange', val);
      updateSchema([
        { field: 'detailContent', ifShow: val == 2 },
        { field: 'newsUrl', ifShow: val != 2 },
      ]);
    }
    const handleSubmit = async () => {
      const params = await validate();
      const apiData = {
        ...(params as any),
        coverImageUrl: params.coverImageUrl && params.coverImageUrl[0],
        logo: params.logo && params.logo[0],
      };
      try {
        await caseaddOrUpdateApi(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>
