<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    @ok="handleOk"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="model" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { checkUserApi, saveApi, updateApi, getRoleListByParam } from '/@/api/staff/list'; //roleLIstApi
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { ListAllCompanyApi } from '/@/api/corporation/list';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['ok'],
    setup(_, context) {
      const modelRef = ref({});
      const userStore = useUserStore();
      const { getCheckRole } = userStore;
      const userinfo = computed(() => userStore.getUserInfo);
      const { companyId } = userinfo.value;
      console.log('companyId', companyId);
      const schemas: FormSchema[] = [
        {
          field: 'phone',
          component: 'Input',
          label: t('routes.corporation.phone'),
          colProps: {
            span: 18,
          },
          // helpMessage: '手机号需在指房宝APP注册后才可新增',
          required: false,
          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) {
                  return Promise.reject(t('common.phone'));
                }
                if (!reg_tel.test(value)) {
                  /* eslint-disable-next-line */
                  return Promise.reject(t('common.phoneError'));
                }
                try {
                  let res = await checkUserApi({ phone: value });
                  console.log('res', res);
                  if (res == true) {
                    return Promise.resolve();
                  } else {
                    return Promise.reject(t('routes.staff.addTips'));
                  }
                } catch (err) {
                  return Promise.reject(err);
                }
              },
              trigger: 'change',
            },
          ],
        },
        {
          field: 'nickName',
          component: 'Input',
          label: t('routes.staff.userName'),
          colProps: {
            span: 22,
          },
          componentProps: {
            maxLength: 15,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                var reg_tel = /^[a-zA-Z0-9\u4e00-\u9fa5()]+$/;
                // var reg = /\S+@\S+\.\S+/;
                if (!value) {
                  return Promise.reject(t('common.userNick'));
                }
                if (!reg_tel.test(value)) {
                  /* eslint-disable-next-line */
                  return Promise.reject(t('common.userCorrectNameNick'));
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
        },
        {
          field: 'companyId',
          label: t('routes.staff.companyId'),
          component: 'ApiSelect',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: true,
          ifShow: getCheckRole('plat_admin'),
          componentProps: {
            api: ListAllCompanyApi,
            showSearch: true,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
            },
            required: true,
          },
        },
        {
          field: 'roleId',
          component: 'ApiSelect',
          label: t('common.roleName'),
          required: true,
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          defaultValue: 8,
          componentProps: {
            options: [
              {
                label: t('routes.staff.roleType.1'),
                value: 8,
                key: 8,
              },
            ],
          },
        },
        {
          field: 'permList',
          component: 'ApiSelect',
          label: t('routes.staff.permList'),
          colProps: {
            span: 22,
          },
          componentProps: {
            api: async function (params) {
              const res = await getAllList(params);
              console.log('params', params, res);
              // const treeData = makeTree(res);
              return res.map((i) => {
                return {
                  ...i,
                  permName: i.permName + '  ' + i.createTime,
                };
              });
            },
            labelField: 'permName',
            valueField: 'id',
            immediate: true,
            mode: 'multiple',
            params: {
              page: 1,
              limit: 100,
              // companyId:
            },
            required: true,
          },
        },
        // {
        //   field: 'status',
        //   label: '状态',
        //   component: 'RadioButtonGroup',
        //   required: true,
        //   defaultValue: 1,
        //   itemProps: {
        //     validateTrigger: 'blur',
        //   },
        //   componentProps: {
        //     options: [
        //       { label: '是', value: 1 },
        //       { label: '否', value: 0 },
        //     ],
        //   },
        // },
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },
      ];
      const title = ref(t('routes.staff.add'));
      const { createMessage } = useMessage();
      const [registerForm, { setFieldsValue, validate, updateSchema, resetFields }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        // 方式1;
        console.log('useModalInner', data);
        setFieldsValue({
          ...data,
          roleId: data.roleId != 2 ? data.roleId : '',
        });
        let setSchema = [
          {
            field: 'roleId',
            component: 'ApiSelect',
            componentProps: {
              disabled: false,
              api: getRoleListByParam,
              labelField: 'roleName',
              valueField: 'roleId',
              params: {
                type: data.roleId ? 1 : 0,
                roleId: data.roleId,
              },
            },
          },
          {
            field: 'phone',
            componentProps: {
              disabled: data.id ? true : false,
            },
          },
          {
            field: 'companyId',
            componentProps: {
              disabled: data.id ? (data.roleId != 2 ? true : false) : false,
            },
          },
        ];
        title.value = data.id ? t('common.edit') : t('routes.devices.add');
        updateSchema(setSchema);
      }

      async function handleOk() {
        let data = await validate();
        const requestApi = data.id ? updateApi : saveApi;
        let res = await requestApi({
          ...data,
          userName: data.phone,
          phone: data.phone,
          nickName: data.nickName,
          roleId: data.roleId,
          id: data.id,
        });
        console.log('res', res);
        context && context.emit('ok', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }

      return { register, title, schemas, registerForm, model: modelRef, handleOk, resetFields };
    },
  });
</script>
