<template>
  <a-modal
    v-model:visible="visible"
    :maskClosable="false"
    :width="580"
    :bodyStyle="{ height: '480px', 'overflow-y': 'auto' }"
    cancelText="取消"
    okText="确定"
    @ok="handleOk"
  >
    <template #title>
      <div ref="modalTitleRef" style="width: 100%; cursor: move">
        {{ isAdd ? "添加设备" : "编辑设备" }}
      </div>
    </template>
    <template #modalRender="{ originVNode }">
      <div :style="transformStyle">
        <component :is="originVNode" />
      </div>
    </template>
    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      label-align="left"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
      layout="vertical"
    >
      <!-- <a-form-item  :wrapper-col="{ offset: 0, span: 24 }"
        label="ID"
        name="id"
        :rules="[{ required: false, message: '请输入设备编号！' }]">
        <a-input size="large" v-model:value="formState.id" />
      </a-form-item> -->

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="产品"
        name="productId"
        :rules="[{ required: true, message: '请输入设备名称！' }]"
      >
        <!-- <a-input size="large" v-model:value="formState.productId" /> -->
        <a-select
          size="large"
          v-model:value="formState.productId"
          :options="options"
        ></a-select>
      </a-form-item>

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="设备编号"
        name="mac"
        :rules="[{ required: true, message: '请输入设备编号！' }]"
      >
        <a-input size="large" v-model:value="formState.mac" />
      </a-form-item>

      <!-- <a-form-item  :wrapper-col="{ offset: 0, span: 24 }"
        label="设备名称"
        name="name"
        :rules="[{ required: true, message: '请输入设备名称！' }]">
        <a-input size="large" v-model:value="formState.name" />
      </a-form-item> -->

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="IP"
        name="ipAddress"
      >
        <a-input size="large" v-model:value="formState.ipAddress" />
      </a-form-item>

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="网关"
        name="gateWay"
      >
        <a-input size="large" v-model:value="formState.gateWay" />
      </a-form-item>

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="子网掩码"
        name="netMask"
      >
        <a-input size="large" v-model:value="formState.netMask" />
      </a-form-item>

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="通信MAC"
        name="netMac"
      >
        <a-input size="large" v-model:value="formState.netMac" />
      </a-form-item>

      <a-form-item
        :wrapper-col="{ offset: 0, span: 24 }"
        label="描述"
        name="description"
        :rules="[{ required: false, message: '请输入设备名称！' }]"
      >
        <!-- <a-input size="large" v-model:value="formState.name" /> -->
        <a-textarea
          v-model:value="formState.description"
          placeholder="请输入描述"
          allow-clear
        />
      </a-form-item>

      <!-- <a-form-item :wrapper-col="{ offset: 0, span: 24 }">
        <a-button  style="background: #0058FF;"
          size="large" block type="primary" html-type="submit">登录</a-button>
      </a-form-item> -->
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  CSSProperties,
  watch,
  watchEffect,
  onMounted,
  onUnmounted,
  reactive,
} from "vue";
import { AddDeviceParams } from "@/api/model";
import { post } from "@/network/axios";
import { message } from "ant-design-vue";
import { resetProperties } from "@/utils";
import { useDraggable } from "@vueuse/core";

const modalTitleRef = ref<HTMLElement>();
const formRef = ref<any>(null);
const visible = ref<boolean>(false);
const isAdd = ref<boolean>(true);
const { x, y, isDragging } = useDraggable(modalTitleRef);

// 属性
// const props = defineProps()
// 事件
const emits = defineEmits(["onSuccess"]);

// 选项
const options = reactive<any[]>([
  {
    value: "123",
    label: "网络泵",
  },
  {
    value: "456",
    label: "化疗泵",
  },
  {
    value: "789",
    label: "其他",
  },
]);

// 添加
const formState = reactive<AddDeviceParams>({
  id: undefined,
  mac: "",
  name: "",
  productId: "",
  netMac: "",
  description: "",
  gateWay: "",
  netMask: "",
  ipAddress: "",
});
const save = function () {
  let url = "";
  if (isAdd.value) {
    url = "/device/add";
  } else {
    url = "/device/edit";
  }
  post({ url, data: formState }, (result: any) => {
    console.log(result);
    message.info(result.msg);
    hidden();
    emits("onSuccess", result);
  });
};

const handleOk = (e: MouseEvent) => {
  console.log("handleOK", e);
  formRef.value?.validate().then(
    () => {
      console.log("11");
      save();
    },
    () => {
      console.log("22");
    }
  );
};

const show = () => {
  visible.value = true;
};
const hidden = () => {
  visible.value = false;
};
const add = () => {
  isAdd.value = true;
  resetProperties(formState);
  formRef.value?.clearValidate();
  show();
};
const update = (record: any) => {
  isAdd.value = false;
  record.id = record.deviceId;
  Object.assign(formState, record);
  formRef.value?.clearValidate();
  show();
};

// 声明周期
onMounted(() => {
  console.log("onMounted");
  options.splice(0);
  post(
    {
      url: "/product/search",
      data: {
        size: 20,
        page: 1,
        sort: "createtime",
        order: "desc",
      },
    },
    (result: any) => {
      console.log(result);
      result.data.forEach((item: any) => {
        const option = {
          value: item.code,
          label: item.name,
        };
        options.push(option);
      });
    },
    (failed: any) => {
      console.log(failed);
    }
  );
});
onUnmounted(() => {
  console.log("onUnmounted");
});

defineExpose({
  add,
  update,
});

//拖拽

const startX = ref<number>(0);
const startY = ref<number>(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({ left: 0, right: 0, top: 0, bottom: 0 });
watch([x, y], () => {
  if (!startedDrag.value) {
    startX.value = x.value;
    startY.value = y.value;
    const bodyRect = document.body.getBoundingClientRect();
    const titleRect = modalTitleRef.value.getBoundingClientRect();
    dragRect.value.right = bodyRect.width - titleRect.width;
    dragRect.value.bottom = bodyRect.height - titleRect.height;
    preTransformX.value = transformX.value;
    preTransformY.value = transformY.value;
  }
  startedDrag.value = true;
});
watch(isDragging, () => {
  if (!isDragging) {
    startedDrag.value = false;
  }
});

watchEffect(() => {
  if (startedDrag.value) {
    transformX.value =
      preTransformX.value +
      Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) -
      startX.value;
    transformY.value =
      preTransformY.value +
      Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) -
      startY.value;
  }
});
const transformStyle = computed<CSSProperties>(() => {
  return {
    transform: `translate(${transformX.value}px, ${transformY.value}px)`,
  };
});
</script>

<style scoped></style>
