<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="将设备分配给客户"
    :canFullscreen="false"
    centered
    @ok="dispatchCustomer"
    @cancel="resetFields"
    :minHeight="300"
    okText="分配"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { customerForm } from '../../config/detail.config';
  import { dispatchCustomer as dispatchCustomerApi } from '/@/api/device/deviceManager';
  import { DeviceModel } from '/@/api/device/model/deviceModel';
  import { isArray } from '/@/utils/is';
  export default defineComponent({
    name: 'AlarmDetailModal',
    components: {
      BasicModal,
      BasicForm,
    },
    emits: ['reload', 'register'],
    setup(_, { emit }) {
      let record: DeviceModel[] = [];
      const [registerModal, { closeModal }] = useModalInner((data: DeviceModel | DeviceModel[]) => {
        data = isArray(data) ? data : [data as DeviceModel];
        const { organizationId } = data.at(0) || {};
        record = data;
        updateSchema([
          {
            field: 'customerId',
            componentProps: {
              params: { organizationId },
            },
          },
        ]);
      });
      const [registerForm, { validate, getFieldsValue, updateSchema, resetFields }] = useForm({
        labelWidth: 100,
        showActionButtonGroup: false,
        schemas: customerForm,
      });
      // 分配客户
      const dispatchCustomer = async () => {
        await validate();
        const { customerId } = getFieldsValue();
        const task: Promise<any>[] = [];
        for (const item of record) {
          task.push(dispatchCustomerApi({ ...item, customerId }));
        }
        await Promise.all(task);
        closeModal();
        resetFields();
        emit('reload');
      };

      return {
        registerModal,
        registerForm,
        dispatchCustomer,
        resetFields,
      };
    },
  });
</script>
