<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>
    <DynamicForm :prem="formSystem" />

    <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 DynamicForm from '@/components/dynamic-form/index.vue';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
  import { IEditorConfig } from '@wangeditor/editor'
  import '@wangeditor/editor/dist/css/style.css'

  const props = defineProps({
    prem: {
      type: Object as PropType<CreateRecord>,
    },
    isCreate: Boolean,
  });
  // 部门树模态框状态
  const deptVisible=ref(false);
  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 messageStore = useMessageStore();
  const editorRef = shallowRef()
  const selectedIds= ref<string[]>([]);
  const columns = computed<any[]>(()=>[
    {
      title: '操作',
      dataIndex: 'key',
      slotName: 'key',
    },
    {
      title: '用户',
      dataIndex: 'title',
    },
  ])

  const formSystem = ref(
    {
      productId:{
        label: '产品ID',
        component: 'input',
        type:'text'
      },
      name:{
        label: '设备名称',
        component: 'input',
        type:'text'
      },
      hardwareVersion:{
        label: '硬件版本',
        component: 'input',
        type:'text'
      },
      firmwareVersion:{
        label: '固件版本',
        component: 'input',
        type:'text'
      },
      extendParams:{
        label: '扩展属性',
        component: 'input',
        type:'text'
      },
      properties:{
        label: '设备物模型属性',
        component: 'input',
        type:'text'
      },
    },
  );
  const deptTreeData = reactive([
    {
      key: '1',
      title: '总部门',
      children: [
        {
          key: '2',
          title: '部门1',
          members: [
            { key: '101', title: '成员1' },
            { key: '102', title: '成员2' }
          ]
        },
        {
          key: '3',
          title: '部门2',
          members: [
            { key: '201', title: '成员3' },
            { key: '202', title: '成员4' }
          ]
        },
        {
          key: '4',
          title: '部门3',
          members: [
            { key: '203', title: '成员5' },
            { key: '204', title: '成员6' }
          ]
        }
      ]
    }
  ]);
  const selectedDepartmentMembers: any = ref([]);
  const renderData = ref<any[]>([]);
  // 部门树查询
  const queryDeptTree= async ()=>{
    deptVisible.value = true;
  }

  // 广度优先遍历树，获取选中的成员
  const getSelectedMembers = (treeData: any[], selectedKeys: string[]) => {
    const queue = [...treeData];
    const selectedMembers: any[] = [];
    while (queue.length > 0) {
      const node = queue.shift()!;
      if (selectedKeys.includes(node.key)) {
        if (node.members) {
          selectedMembers.push(...node.members);
        }
      }
      if (node.children) {
        queue.push(...node.children);
      }
    }
    return selectedMembers;
  }

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

  const editorConfig: Partial<IEditorConfig> = { placeholder: '请输入内容...',MENU_CONF:{
      // 隐藏菜单
      hide: ['code', 'table', 'emoticon', 'uploadImage', 'video', 'todo', 'specialChar'],
      // 配置上传图片
      uploadImage: {
        base64LimitSize: 1024 * 1024,
        // server: '/api/rest/bulletin/1/add',
      }
    }
  }
  // 提交
  const handleSubmit = async () => {
    const valid = await CreateRef.value?.validate();
    if (!valid) {
      formData.value.permissionIds = checkKeys.value;
      // 新增
      if (props.isCreate) {
        // formData.value.username = formData.value.email;
        const res = await messageStore.createMessage(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '新建成功',
            duration: 5 * 1000,
          });
          emit('refresh');
          setVisible(false);
        }
        CreateRef.value?.resetFields();
      }
    }
  };

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

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

  // 设备模态框提交
  const deptTreeSubmit = () => {
    deptVisible.value = false;
    formData.value.userIds = selectedIds.value;
    console.log(formData.value.userIds);
  };
</script>

<style scoped>
  .fullscreen-toolbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 50px; /* 根据需要调整高度 */
    z-index: 999;
    background-color: white;
  }
  .fullscreen-editor {
    position: fixed;
    top: 50px; /* 根据 toolbar 的高度调整 */
    left: 0;
    width: 100%;
    height: calc(100% - 50px); /* 减去 toolbar 的高度 */
    z-index: 999;
    background-color: white;
  }
  .editor-button{
    position: static
  }
</style>
