<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.corporation.addCorporation')"
    @visible-change="handleVisibleChange"
    @ok="handleSubmit"
    @cancel="resetFields"
  >
    <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 dayjs from 'dayjs';
  // import { checkUserAddAble } from '/@/api/corporation/modal';
  import { data as CascaderData } from '/@/utils/cascaderData';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadLogoApi, saveCompanyApi } from '/@/api/corporation/list';
  const { t } = useI18n();
  const schemas: FormSchema[] = [
    {
      field: 'name',
      component: 'Input',
      required: true,
      label: t('routes.corporation.enterpriseName'),
      componentProps: {
        maxLength: 20,
      },
      colProps: {
        span: 22,
      },
    },
    {
      field: 'contacts',
      component: 'Input',
      label: t('routes.corporation.managerName'),
      required: true,
      componentProps: {
        maxLength: 18,
      },
      colProps: {
        span: 22,
      },
    },
    {
      field: 'phone',
      component: 'Input',
      label: t('common.mobile'),
      rules: [
        {
          required: true,
          // @ts-ignore
          validator: async (rule, value) => {
            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}$/;
            // var reg = /\S+@\S+\.\S+/;
            if (!value) {
              /* eslint-disable-next-line */

              return Promise.reject(t('common.phone'));
            }
            if (!reg_tel.test(value)) {
              /* eslint-disable-next-line */
              return Promise.reject(t('common.phoneError'));
            }
            return Promise.resolve();
          },
          trigger: 'change',
        },
      ],
      colProps: {
        span: 22,
      },
    },
    {
      field: 'area',
      label: '地区',
      component: 'ApiCascader',
      componentProps: {
        api: () => {
          return CascaderData;
        },
        apiParamKey: 'provinceCode',
        dataField: 'children',
        labelField: 'name',
        valueField: 'name',
        // numberToString: true,
        isLeaf: (record) => {
          return !(record.levelType < 3);
        },
        onChange: (data) => {
          console.log('data', data);
        },
      },
      colProps: {
        span: 22,
      },
    },
    {
      field: 'address',
      component: 'Input',
      label: t('routes.corporation.address'),
      required: true,
      colProps: {
        span: 22,
      },
      componentProps: {
        maxLength: 50,
      },
    },
    {
      field: 'website',
      component: 'Input',
      label: t('routes.corporation.website'),
      required: true,
      colProps: {
        span: 22,
      },
      componentProps: {
        maxLength: 50,
      },
    },
    {
      field: 'expirationTime',
      component: 'DatePicker',
      label: t('routes.corporation.expirationTime'),
      required: true,
      colProps: {
        span: 22,
      },
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
        disabledDate: (current) => {
          return current && current < dayjs().endOf('day');
        },
      },
    },
    {
      field: 'logo',
      component: 'Upload',
      label: t('routes.corporation.companyLogo'),
      required: true,
      rules: [{ required: true, message: '请选择上传文件' }],
      helpMessage: '支持png  jpg图片格式',
      itemProps: {
        validateTrigger: 'blur',
      },
      componentProps: {
        api: uploadLogoApi,
        maxNumber: 1,
        maxSize: 10,
        accept: ['jpg', 'jpeg', 'gif', 'png'],
        afterFetch: function (data) {
          console.log('data', data);
          Reflect.set(data, 'url', data.message);
          return data;
        },
      },

      colProps: {
        span: 22,
      },
    },
    {
      field: 'qualification',
      component: 'Upload',
      label: t('routes.corporation.qualification'),
      required: true,
      rules: [{ required: true, message: '请选择上传文件' }],
      itemProps: {
        validateTrigger: 'blur',
      },
      helpMessage: '支持png  jpg图片格式',
      componentProps: {
        api: uploadLogoApi,
        maxNumber: 1,
        maxSize: 10,
        accept: ['jpg', 'jpeg', 'gif', 'png'],
        afterFetch: function (data) {
          console.log('data', data);
          Reflect.set(data, 'url', data.message);
          return data;
        },
      },

      colProps: {
        span: 22,
      },
    },
    {
      field: 'introduce',
      component: 'InputTextArea',
      label: t('routes.corporation.introduce'),
      required: true,
      colProps: {
        span: 22,
      },
      componentProps: {
        maxLength: 200,
      },
    },
  ];
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'submit'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const { createMessage } = useMessage();
      const [
        registerForm,
        {
          // getFieldsValue,
          // setFieldsValue,
          // setProps
          resetFields,
          validate,
        },
      ] = 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 handleSubmit = async () => {
        const values = await validate();

        const insertData = {
          ...values,
          area: values.area.join(' '),
          logo: values.logo[0],
          qualification: values.qualification[0],
        };
        console.log('insertData', values);
        //TODO hack parameter
        const res = await saveCompanyApi(insertData);
        // let res = await checkUserAddAble({ phoneNum: values.managerPhone });
        console.log('res', res);
        emit('submit');
        closeModal();
        resetFields();
        createMessage.success(t('common.optSuccess'));
        // createMessage.success(t('routes.corporation.optSuccess'));
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

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