<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    :width="600"
    @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 } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { agentNewAdd, checkUser } from '/@/api/dealer'
  import { useI18n } from '/@/hooks/web/useI18n';

  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 preventAutoFill = ref(true);
      const fileFlow = reactive({
        coverImageUrl:''
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'name',
          component: 'Input',
          label: '经销商名称',
          required: true,
          componentProps: {
            maxlength: 50,
          },
          colProps: {
            span: 22,
          },
        },{
            field: 'nickName',
            component: 'Input',
            required: false,
            label: '联系人',
            componentProps: {
              maxlength: 50,
            },
            colProps: {
              span: 22,
            },
        },{
            field: 'userName',
            component: 'Input',
            label: '账号',
            required: true,
            componentProps: {
              placeholder:"请输入四维看看账号",
              autoComplete:'off',
              // readonly:preventAutoFill.value
            },
            rules: [
              {
                required: true,
                // @ts-ignore
                validator: async (rule, value) => {
                  console.log('value',value)
                  const regPos = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/; // 非中文
                  if (!value) {
                    return Promise.reject('请输入四维看看账号');
                  }
                  if (!regPos.test(value)) {
                    /* eslint-disable-next-line */
                    return Promise.reject('请输入正确的手机号');
                  }
                  let res = await checkUser({userName:value})
                  if(!res){
                    return Promise.reject('用户不存在');
                  }
                  return Promise.resolve();
                },
                trigger: 'change',
              },
            ],
            colProps: {
              span: 22,
            },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue }] = 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 = content.replace(/ /ig, ''); /* 去除  */    
          content = content.replace(/\s/ig, ''); /* 去除空格 */
          return content && content.length;
      }
      async function onDataReceive(data) {
        modelRef.value = data
        resetFields();
      }
      const handleSubmit = async () => {
        const params = await validate();
        const apiData = {
          ...params as any,
          coverImageUrl:params.coverImageUrl && params.coverImageUrl[0],
          content:params.newType == 1?params.newsUrl:params.content
        }
        try {
          await agentNewAdd(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,
        preventAutoFill,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        title,
        t,
      };
    },
  });
</script>
