<template>
  <div class="modals">
    <BasicModal
      v-bind="$attrs"
      destroyOnClose
      @register="registerModal"
      :title="getTitle"
      @ok="handleSubmit"
      :width="880"
      @cancel="handleCancel"
    >
      <div class="!pl-8 !pt-4">
        <BasicForm @register="registerForm">
          <template #deviceInfo="{ model, field }">
            <span>&nbsp;&nbsp;&nbsp;&nbsp;{{ model[field] }}</span>
          </template>
        </BasicForm>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { dataFormSchema } from './data';
  import {
    microbialDetectionWaterAdd,
    microbialDetectionWaterEdit,
    microbialDetectionWaterDetail,
  } from '/@/api/biz/bio/microbialDetectionWaterApi';
  import { waterDetail } from '@/api/biz/engineer/waterApi';
  const emit = defineEmits(['success', 'cancel', 'register']);
  const getTitle = computed(() => (!unref(isUpdate) ? '新增检测' : '编辑检测'));
  const isUpdate = ref(false);
  const rowId = ref();
  const { createMessage } = useMessage();
  const [registerForm, { resetFields, validate, setFieldsValue }] = useForm({
    layout: 'vertical',
    showResetButton: true,
    labelWidth: 320,
    schemas: dataFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
    baseColProps: {
      span: 12,
    },
    wrapperCol: {
      span: 22,
    },
  });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      const resData = await microbialDetectionWaterDetail(data.record.id);
      const deviceInfos = await waterDetail(resData?.deviceId);
      resData.deviceInfo = deviceInfos?.name + '(' + deviceInfos?.model + ')';
      console.log('resData::::', resData);
      await setFieldsValue({
        ...resData,
      });
    }
  });

  // 提交按钮事件
  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      !unref(isUpdate)
        ? await microbialDetectionWaterAdd({ ...values })
        : await microbialDetectionWaterEdit({ ...values, id: rowId.value });
      !unref(isUpdate) ? createMessage.success('新增成功！') : createMessage.success('编辑成功！');
      closeModal();
      emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } finally {
      setModalProps({ confirmLoading: false, canFullscreen: false });
    }
  }

  async function handleCancel() {
    closeModal();
    emit('cancel');
  }
</script>
<style lang="less" scoped>
  ::v-deep(.ant-modal) {
    background-color: #000;
  }
</style>
