<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm">
      <template #user="{ model }">
        <SelectUser
          v-model:value="model.checkedUserIds"
          suffix="ant-design:setting-outlined"
          placeholder="请选择巡检人"
        />
      </template>
      <template #upload="{ model }">
        <Upload v-model:value="model.filePath" listType="picture" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import {
    addDeviceInspect,
    updateDeviceInspect,
    getDeviceInspectInfo,
  } from '/@/api/erp/device/inspect';
  import { getDeviceInfoByTypeId } from '/@/api/erp/device/info';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import Upload from '/@/components/Form/src/components/Upload.vue';

  const { t } = useI18n();

  const FormSchema: FormSchema[] = [
    {
      field: 'typeId',
      label: '设备类型',
      component: 'DicSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择设备类型',
        itemId: '1671412696707850241',
        isShowAdd: false,
        onChange: (value) => {
          if (value) {
            updateSchema({
              field: 'deviceId',
              componentProps: {
                placeholder: '请选择设备名称',
                api: getDeviceInfoByTypeId,
                params: value,
                labelField: 'name',
                valueField: 'id',
                getPopupContainer: () => document.body,
              },
            });
          }
        },
      },
    },
    {
      field: 'number',
      label: '设备编号',
      component: 'Input',
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入设备编号',
        disabled: true,
      },
    },
    {
      field: 'deviceId',
      label: '设备名称',
      component: 'ApiSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择设备名称',
        onChange: (_, option) => {
          setFieldsValue({ number: option?.number, model: option?.model });
        },
      },
    },
    {
      field: 'model',
      label: '规格型号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入规格型号',
        disabled: true,
      },
    },
    {
      field: 'checkedUserIds',
      label: '巡检人',
      component: 'Input',
      slot: 'user',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'date',
      label: '巡检时间',
      component: 'DatePicker',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        format: 'YYYY-MM-DD',
        placeholder: '请选择巡检时间',
      },
    },
    {
      field: 'natureId',
      label: '检查性质',
      component: 'DicSelect',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请选择检查性质',
        itemId: '1679045876047552513',
        isShowAdd: false,
      },
    },
    {
      field: 'result',
      label: '检查结果',
      component: 'InputTextArea',
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入检查结果',
      },
    },
    {
      field: 'filePath',
      label: '上传附件',
      component: 'Upload',
      slot: 'upload',
      colProps: { span: 24 },
    },
    {
      field: 'state',
      label: '选择状态',
      component: 'RadioGroup',
      // slot: 'state',
      colProps: { span: 24 },
      componentProps: {
        options: [
          { label: '通过', value: 1 },
          { label: '未通过', value: 0 },
        ],
      },
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    layout: 'vertical',
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getDeviceInspectInfo(data.id);
      setFieldsValue({
        ...record,
      });
    } else {
      setFieldsValue({
        state: 1,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增巡检' : '编辑巡检'));

  const handleSubmit = async () => {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addDeviceInspect(values);
        notification.success({
          message: '新增巡检',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateDeviceInspect(values);
        notification.success({
          message: '编辑巡检',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
