<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.archive.restore')"
    width="700px"
    :minHeight="250"
    :centered="true"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="pt-10px pb-60px">
      <BasicForm @register="registerForm" />
    </div>
    <template #centerFooter>
      <!-- <a-button>xxxx</a-button> -->
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';

  import { getAllAccountListApi, getCameraListApi, restoreApi } from '/@/api/archive/resstore';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';

  const { t } = useI18n();
  const { createMessage } = useMessage();

  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['register', 'success', 'cancel'],
    setup(_, { emit }) {
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      const selectData = ref({
        account: '',
        tableType: NaN,
        num: [],
      });
      const schemas: FormSchema[] = [
        {
          field: 'userName',
          label: t('routes.archive.restoreUserName'),
          component: 'ApiSelect',
          required: true,
          componentProps: {
            api: getAllAccountListApi,
            // resultField: 'list',
            numberToString: true,
            labelField: 'userName',
            valueField: 'userName',
            showSearch: true,
            optionFilterProp: 'label',
            immediate: false,
            listHeight: 160,
            allowClear: true,
            getPopupContainer: (node) => {
              if (node) {
                return node.parentNode;
              } else {
                return document.body;
              }
            },
            onChange: (data) => {
              console.log('data', data);
              if (data) {
                selectData.value.account = data;
                clearValidate(['userName']);
              } else {
                selectData.value.account = '';
              }
              removeSchemaByField('cameraId');
              appendSchemaByField(schemas[1], 'cameraId');
            },
            params: {
              page: 1,
              limit: 1000,
            },
          },
        },
        {
          field: 'cameraId',
          label: t('routes.archive.restoreCarmeraId'),
          component: 'ApiSelect',
          required: true,
          componentProps: {
            api: async (params) => {
              console.log('params', params);
              if (!selectData.value.account) {
                createMessage.error(t('routes.archive.selectCameraFirst'));
                return;
              } else {
                const res = await getCameraListApi({
                  userName: selectData.value.account,
                  type: selectData.value.tableType,
                });
                return res;
              }
            },
            // resultField: 'list',
            numberToString: true,
            labelField: 'snCode',
            valueField: 'id',
            immediate: false,
            listHeight: 160,
            showSearch: true,
            placeholder: t('routes.archive.rsPlaceHolder'),
            optionFilterProp: 'label',
            getPopupContainer: (node) => {
              if (node) {
                return node.parentNode;
              } else {
                return document.body;
              }
            },
            onChange: (data) => {
              if (data) {
                console.log('snCode', data);
                clearValidate();
              }
            },
            params: {
              page: 1,
              limit: 1000,
            },
          },
        },
      ];
      const [
        registerForm,
        {
          validate,
          clearValidate,
          getFieldsValue,
          resetFields,
          appendSchemaByField,
          removeSchemaByField,
        },
      ] = useForm({
        schemas: schemas,
        labelWidth: 150,
        baseColProps: { span: 22 },
        autoSubmitOnEnter: true,
        showResetButton: false,
        showSubmitButton: false,
        submitFunc: async () => {},
      });

      const checked = ref<boolean>(false);
      const headerInfo = reactive<Recordable>({});
      const searchInfo = reactive<Recordable>({});

      function onDataReceive(data: any) {
        console.log('Data Received', data);
        selectData.value.tableType = Number(data.tableType);
        selectData.value.num = data.sceneNum;
      }

      const handleSelect = async () => {
        // const keys = getSelectRowKeys();
        // console.log('key', key);
      };
      const handleChange = (val, row) => {
        console.log('val,row', val, row);
      };
      const handleSubmit = async () => {
        try {
          await validate();
          const fields = getFieldsValue();
          await restoreApi({
            numList: selectData.value.num,
            cameraId: fields.cameraId,
            userName: fields.userName,
          });
          createMessage.success(t('common.optSuccess'));
          resetFields();
          closeModal();
          emit('success');

          setTimeout(() => {
            createMessage.destroy();
          }, 3000);
        } catch (error) {
          console.error('error', error);
        }
      };
      const handleCancel = async () => {
        selectData.value.account = '';
        selectData.value.tableType = NaN;
        selectData.value.num = [];
        removeSchemaByField('cameraId');
        appendSchemaByField(schemas[1], 'cameraId');
        resetFields();
        emit('cancel');
      };

      return {
        register,
        searchInfo,
        closeModal,
        handleSelect,
        headerInfo,
        handleChange,
        t,
        checked,
        handleSubmit,
        registerForm,
        handleCancel,
        clearValidate,
      };
    },
  });
</script>
