<template>
  <a-button v-if="props.isCreate" type="primary" @click="handleClick">
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-button
    v-if="!props.isCreate"
    type="outline"
    size="small"
    :style="{ marginRight: '10px', padding: '7px' }"
    @click="handleClick"
  >
    <template #icon><icon-edit /></template>
    修改
  </a-button>

  <a-modal
    width="900px"
    :visible="visible"
    @cancel="handleCancel"
  >
    <template #title>{{ modalTitle }}</template>
    <a-form
      ref="CreateRef"
      :model="formData"
      :style="{ width: '650px' }"
    >
      <!-- 产品id -->
      <a-form-item
        field="productId"
        label="产品名称"
        :rules="[{ required: true, message: '产品名称不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-select
          v-model="formData.productId"
          placeholder="请选择产品名称"
          :loading="loading"
          :filter-option="false"
          @search="handleSearch"
        >
          <a-option v-for="item of options" :key="item.id" :value="item">{{item}}</a-option>
        </a-select>
      </a-form-item>
      <!-- 设备名称 -->
      <a-form-item
        field="name"
        label="设备名称"
        :rules="[{ required: true, message: '设备名称不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-input
          v-model="formData.name"
          placeholder='请输入设备名称'
        />
      </a-form-item>
      <!-- 硬件版本 -->
      <a-form-item
        field="hardwareVersion"
        label="硬件版本"
        :rules="[{ required: true, message: '硬件版本不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-input
          v-model="formData.hardwareVersion"
          placeholder='请输入硬件版本'
        />
      </a-form-item>
      <!-- 固件版本 -->
      <a-form-item
        field="firmwareVersion"
        label="固件版本"
        :rules="[{ required: true, message: '固件版本不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-input
          v-model="formData.firmwareVersion"
          placeholder='请输入固件版本'
        />
      </a-form-item>
      <!-- 扩展属性 -->
      <a-form-item
        field="extendParams"
        label="扩展属性"
        :rules="[{ required: true, message: '扩展属性不能为空' }]"
        :validate-trigger="['change']"
      >
        <a-input
          v-model="formData.extendParams"
          placeholder='请输入扩展属性'
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button class="editor-button"  @click="handleCancel">取消</a-button>
      <a-button class="editor-button"  type="primary" @click="handleSubmit">确定</a-button>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { computed, defineEmits, PropType, ref, shallowRef, onBeforeUnmount, reactive } from 'vue';
  import { CreateRecord } from '@/api/user';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import { useMessageStore } from '@/store';
  import '@wangeditor/editor/dist/css/style.css'
  import { createDevice, updateDevice } from '@/api/device';

  const props = defineProps({
    prem: {
      type: Object as PropType<CreateRecord>,
    },
    isCreate: Boolean,
  });
  const emit = defineEmits(['refresh']);
  const modalTitle = computed(() => {
    return props.isCreate ? '创建设备' : '编辑设备';
  });
  const { visible, setVisible } = useVisible(false);
  const checkKeys = ref<number[]>([]);

  const CreateRef = ref<FormInstance>();
  const formData = ref<any>({
    ...props.prem,
  });
  const editorRef = shallowRef()
  const options = ref(['Option1', 'Option2', 'Option3']);
  const loading = ref(false);

  // 搜索
  const handleSearch = (value: any) => {
    if (value) {
      loading.value = true;
      window.setTimeout(() => {
        options.value = [`${value}-Option1`, `${value}-Option2`, `${value}-Option3`]
        loading.value = false;
      }, 2000)
    } else {
      options.value = []
    }
  };

  // 组件被点击
  const handleClick = () => {
    setVisible(true);
  };

  // 提交
  const handleSubmit = async () => {
    const valid = await CreateRef.value?.validate();
    if (!valid) {
      // 新增
      if (props.isCreate) {
        // formData.value.username = formData.value.email;
        const res = await createDevice(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '新建成功',
            duration: 5 * 1000,
          });
          emit('refresh');
          setVisible(false);
        }
        CreateRef.value?.resetFields();
      } else {
        // 编辑
        const res = await updateDevice(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '修改成功',
            duration: 5 * 1000,
          });
          emit('refresh');
          setVisible(false);
        }
      }
    }
  };

  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })

  // 关闭
  const handleCancel = async () => {
    checkKeys.value = [];
    setVisible(false);
  };

</script>

<style scoped>
  .editor-button{
    position: static
  }
</style>
