<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :confirmLoading="loading"
    :title="fileFlow.title"
    @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 { uploadApi } from '/@/api/product/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isEmojiCharacter } from '/@/utils';
  import { checkUserName, checkjxsUserName } from '/@/api/equity';
  import { addApi, updateApi } from '/@/api/retailer';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const loading = ref(false)
      const fileFlow = reactive({
        file: null,
        title: t('routes.retailer.add'),
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: t('routes.retailer.form.name'),
          show: false,
          colProps: {
            span: 24,
          },
          // required: true,
        },
        {
          field: 'name',
          component: 'Input',
          label: t('routes.retailer.form.name'),
          required: true,
          colProps: {
            span: 24,
          },
          componentProps: {
            maxLength: 50,
          },
        },
        {
          field: 'nickName',
          component: 'Input',
          label: t('routes.retailer.form.nickName'),
          colProps: {
            span: 24,
          },
          componentProps: {
            maxLength: 50,
          },
        },
        {
          field: 'userName',
          component: 'Input',
          label: t('routes.retailer.form.userId'),
          required: true,
          colProps: {
            span: 24,
          },
          componentProps: {
            placeholder:t('routes.retailer.form.userName'),
            maxLength: 50,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                // const regEmail = /^(.+)@(.+)$/;
                // 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(t('routes.retailer.form.userName'));
                }
                // if (!(regPos.test(value) || regEmail.test(value))) {
                //   /* eslint-disable-next-line */
                // return Promise.reject(t('routes.equity.rules.userName1'));
                // }
                // useThrottleFn(handleSplitLeftMenu, 50);
                const res = await checkjxsUserName({ userName: value });
                // useThrottleFn(,50)()
                console.log('validator', res);
                if (!res) {
                  return Promise.reject(t('routes.equity.rules.userName2'));
                }
                return Promise.resolve();
              },
              trigger: 'blur',
            },
          ],
        },
        // {
        //   field: 'orderSn',
        //   component: 'Input',
        //   label: t('routes.devices.orderSn'),
        //   colProps: {
        //     span: 24,
        //   },
        // },
        // {
        //   field: 'companyId',
        //   component: 'ApiSelect',
        //   label: t('routes.devices.companyId'),
        //   itemProps: {
        //     validateTrigger: 'blur',
        //   },
        //   componentProps: {
        //     api: allCompanyApi,
        //     numberToString: true,
        //     labelField: 'name',
        //     valueField: 'id',
        //     immediate: true,
        //     params: {
        //       page: 1,
        //       limit: 1000,
        //     },
        //   },
        //   colProps: {
        //     span: 24,
        //   },
        // },
      ];
      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);
      });
      function renderOwnTypeLabel(type: number): string {
        switch (type) {
          case 9:
            return t('routes.device.type.2');
          case 1:
            return t('routes.device.type.1');
          case 10:
            return t('routes.device.type.3');
          case 11:
            return t('routes.device.type.11');
          default:
            return '';
        }
      }
      function rendercameraTypeLabel(cameraType: number): string {
        switch (cameraType) {
          case 4:
            return t('routes.devices.cameraName.4');
          case 1:
            return t('routes.devices.cameraName.1');
          case 9:
            return t('routes.devices.cameraName.9');
          case 10:
            return t('routes.devices.cameraName.10');
          case 6:
            return t('routes.devices.cameraName.6');
          default:
            return '';
        }
      }
      function onDataReceive(data) {
        modelRef.value = data
        console.log('renderOwnTypeLabel',data)
        fileFlow.title = data.id ? t('routes.retailer.editfxs') : t('routes.retailer.add');
        resetFields();
        updateSchema({
          field: 'userName',
          show: data.id ? false : true,
        })
        setFieldsValue({
          ...data,
        });
      }
      const handleSubmit = async () => {
        loading.value = true
        try {
          const params = await validate();
          let api = params.id ? updateApi : addApi;
          const res = await api(params);
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
          loading.value = false
        } catch (error) {
          loading.value = false
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        rendercameraTypeLabel,
        renderOwnTypeLabel,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        loading,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
