<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.rightsEnterprises.addcamera')"
    @ok="handleOk"
    width="600px"
  >
    <div style="padding-bottom: 90px" class="pt-3px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed } from 'vue';
  import { addCamrea, deviceType } from '/@/api/rightsEnterprises/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 dayjs from 'dayjs';
  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', 'register'],
    setup(_, context) {
      const modelRef = ref({
        isSee: false,
      });
      const userStore = useUserStore();
      const userinfo = computed(() => userStore.getUserInfo);
      const { companyId } = userinfo.value;
      console.log('companyId', companyId);
      const schemas: FormSchema[] = [
        {
          field: 'companyId',
          label: t('routes.rightsEnterprises.companyName'),
          component: 'ApiSelect',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: true,
          componentProps: {
            api: ListAllCompanyApi,
            showSearch: true,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            optionFilterProp: 'label',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
            },
            onOptionsChange: (data) => {
              console.log('data', data, arguments);
            },
            onChange: (data) => {
              console.log('data', data, arguments);
            },
          },
        },
        {
          field: 'userIncrementTypeId',
          label: t('routes.rightsEnterprises.cameraIncrementTypeName'),
          component: 'ApiSelect',
          itemProps: {
            validateTrigger: 'blur',
          },
          colProps: {
            span: 22,
          },
          required: true,
          // ifShow: getCheckRole('plat_admin'),
          componentProps: {
            api: deviceType,
            showSearch: true,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            optionFilterProp: 'label',
            immediate: true,
            params: {
              page: 1,
              limit: 1000,
            },
            required: true,
          },
        },
        {
          label: t('routes.rightsEnterprises.incrementNum'),
          field: 'incrementNum',
          component: 'Input',
          colProps: {
            span: 22,
          },
          componentProps: {
            maxLength: 3,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                var regPos = /(^[1-9]\d*$)/; // 非负整数
                // var reg = /\S+@\S+\.\S+/;
                if (!value) {
                  return Promise.reject('请输入权益数');
                }
                if (!regPos.test(value)) {
                  /* eslint-disable-next-line */
                  return Promise.reject('请输入正确的权益数');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
        },
        {
          field: 'incrementEndTime',
          component: 'DatePicker',
          label: t('routes.rightsEnterprises.expirationTime'),
          colProps: {
            span: 22,
          },
          componentProps: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return current && current < dayjs().endOf('day');
            },
          },
        },
      ];
      const title = ref('绑 定');
      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;
        modelRef.value.isSee = data.userId ? true : false;
        setFieldsValue({
          ...data,
          userId: data.userId ? data.staffName : data.userId,
        });
        let setSchema = [
          {
            field: 'companyId',
            componentProps: {
              disabled: !data.modify,
            },
          },
        ];
        console.log('handleDelete', data, setSchema);
        updateSchema(setSchema);
      }

      async function handleOk() {
        if (modelRef.value.isSee) {
          return closeModal();
        }
        let data = await validate();
        let res = await addCamrea({
          ...data,
        });
        context && context.emit('update', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }

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