<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="新增子账号"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { checkUserAddAble } from '/@/api/corporation/modal';
  const schemas: FormSchema[] = [
    {
      field: 'memoName',
      component: 'Input',
      label: '姓名',
      colProps: {
        span: 24,
      },
    },
    {
      field: 'phone',
      component: 'Input',
      label: '手机号',
      colProps: {
        span: 24,
      },
    },
  ];
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register'],
    setup(props) {
      const modelRef = ref({});
      const { createMessage } = useMessage();
      const [
        registerForm,
        {
          getFieldsValue,
          // setFieldsValue,
          // setProps
        },
      ] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        console.log('Data Received', data);
        const { addList } = data;
        if (typeof addList === 'function') {
          //是函数    其中 FunName 为函数名称
          addListFunc = addList;
        }
      }
      const handleSubmit = async () => {
        console.log('getFieldsValue()', getFieldsValue());
        var reg_tel =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        let { phone, memoName } = getFieldsValue();
        if (phone == '') {
          createMessage.error('请填写您的手机号码！');
          return false;
        } else if (!reg_tel.test(phone)) {
          createMessage.error('请正确填写您的手机号码！');
          return false;
        }
        let res = await checkUserAddAble({ phone });
        if (res.result == false) {
          addListFunc({ phone, memoName });
          closeModal();
        } else {
          createMessage.error('子账号已被该企业绑定');
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        closeModal,
      };
    },
  });
</script>
