<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    title="授权相机"
    @ok="handleOk"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { bindCamera } from '/@/api/rightsEnterprises/list'; //roleLIstApi
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'update'],
    setup(_, context) {
      const { t } = useI18n();
      const modelRef = ref({
        isSee: false,
      });
      const schemas: FormSchema[] = [
        {
          field: 'snCode',
          component: 'Input',
          label: '相机SN码',
          colProps: {
            span: 18,
          },
          required: true,
        },
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },
      ];
      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;
        console.log('handleDelete', data);
        modelRef.value.isSee = data.userId ? true : false;
        setFieldsValue({
          ...data,
          userId: data.userId ? data.staffName : data.userId,
        });
        let setSchema = [
          {
            field: 'userId',
            required: !data.userId,
            slot: !!data.userId ? 'text' : false,
          },
        ];
        updateSchema(setSchema);
      }

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

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