<template>
  <div>
    <a-modal
      v-model:visible="visible"
      width="auto"
      :title="id ? $t('searchTable.form.edit') : $t('searchTable.form.add')"
      @cancel="() => handleCancel()"
      @before-ok="handleBeforeOk"
    >
      <a-form :model="form" auto-label-width ref="formRef">
        <a-row :gutter="8">
          <a-col :span="12">
            <a-form-item
              field="name"
              :label="t('device.form.name')"
              :rules="getRules(t).required"
            >
              <a-input v-model="form.name" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="address"
              :label="t('device.form.address')"
              :rules="getRules(t).required"
            >
              <a-input v-model="form.address" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              field="deviceType"
              :label="t('device.form.entityType')"
              :rules="getRules(t).required"
            >
              <a-select
                v-model="form.deviceType"
                allow-clear
                @clear="form.deviceType = null"
              >
                <a-option
                  v-for="item of deviceTypeList"
                  :value="item.dictCode"
                  :label="item.name"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup lang="ts" name="EditDialog">
import { reactive, ref, shallowRef, watch, getCurrentInstance } from 'vue';
import { getDeviceDetails, saveDeviceDetails } from '@/api/device';
import type { DataList } from '@/api/device';
import type { AdditionalProp } from '@/api/dict';
import { useI18n } from 'vue-i18n';
import { getRules } from '@/utils/const';
import useDictList from '@/hooks/dict-list';
import { useStorage } from '@vueuse/core';
import { STATIONKEY, StationKey } from '@/utils/const';

const formRef = ref();
const { t } = useI18n();

const this_ = getCurrentInstance()?.appContext.config.globalProperties;

interface EditDialogProps {
  modelValue: boolean;
  id: number | null;
}
interface EditDialogEmits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'update-list'): void;
}
const props = withDefaults(defineProps<EditDialogProps>(), {
  modelValue: false,
  id: null,
});
const emit = defineEmits<EditDialogEmits>();
const visible = shallowRef<boolean>(false);
const deviceTypeList = ref<AdditionalProp[]>([] as AdditionalProp[]);
const obj = useStorage<StationKey>(STATIONKEY, {
  id: null,
  station: null,
});
watch(
  () => props.modelValue,
  value => {
    visible.value = value;
    if (value && props.id) {
      getDeviceDetails({ id: props.id }).then(res => {
        form.value = res.data;
      });
    }
  }
);
const formModel = () => {
  return {
    id: 0,
    name: '',
    address: '',
    deviceType: null,
    routeInfoId: null,
  } as DataList;
};
const form = ref<DataList>(formModel());

const handleBeforeOk = (done: (closed: boolean) => void) => {
  formRef.value.validate().then((data: DataList['data']) => {
    if (!data) {
      form.value.routeInfoId = obj.value.id;
      saveDeviceDetails(form.value)
        .then(res => {
          if (res.success) {
            this_?.$message.success(t('message.success'));
            handleCancel();
            done(true); // 关闭模态框
          } else {
            res.message && this_?.$message.error(res.message);
            done(false); // 关闭loading
          }
        })
        .catch(() => {
          done(false); // 不关闭模态框（例如提交失败时）
        });
    } else {
      done(false); // 不关闭模态框（例如提交失败时）
    }
  });
};
useDictList(['DeviceType']).then(res => {
  deviceTypeList.value = res['DeviceType'];
});
const handleCancel = () => {
  form.value = formModel();
  visible.value = false;
  emit('update:modelValue', false);
  emit('update-list');
};
</script>
