<template>
  <a-button v-permission="['message:notice:create']" v-if="props.isCreate" type="primary" @click="handleClick">
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-button
    v-permission="['message:notice:update']"
    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="fieIds" />-->
    <a-form ref="CreateRef" :model="formData" :style="{ width: '650px' }">
      <a-form-item
        field="userId"
        label="用户"
        :validate-trigger="['change', 'input']"
        :rules="[
          { message: '请输入用戶' },
        ]"
      >
        <a-input-tag
          v-model="formData.userIds"
          placeholder='请选择用戶'
          :value=formData.userIds
          @click="queryDeptTree"
        />
      </a-form-item>
      <a-form-item
        field="title"
        label="标题"
        :validate-trigger="['change', 'input']"
        :rules="[
          { required: true, message: '请输入标题' },
        ]"
      >
        <a-input
          v-model="formData.title"
          placeholder='请输入消息标题'
        />
      </a-form-item>
      <a-form-item
        field="remark"
        label="备注"
        :validate-trigger="['change', 'input']"
      >
        <!--        v-if="isCreate"-->
        <a-input
          v-model="formData.attachment"
          placeholder='请输入备注'
        />
      </a-form-item>
      <div style="display: flex;margin-left: 75px">
        <a-form-item
          field="sms"
          label="短信"
          :validate-trigger="['change', 'input']"
        >
          <a-switch
            v-model="formData.sms"
            :checked-value="true"
            :unchecked-value="false"
          />
        </a-form-item>
        <a-form-item
          field="email"
          label="邮件"
          :validate-trigger="['change', 'input']"
        >
          <a-switch
            v-model="formData.email"
            :checked-value="true"
            :unchecked-value="false"
          />
        </a-form-item>

      </div>
<!--      <a-form-item-->
<!--        field="attachmentIds"-->
<!--        label='附件'-->
<!--      >-->
<!--        &lt;!&ndash;        v-if="isCreate"&ndash;&gt;-->
<!--        <a-input-->
<!--          type="file"-->
<!--          v-model="formData.attachmentIds"-->
<!--        />-->
<!--      </a-form-item>-->
      <a-form-item field="content" label='内容' :rules="[{ required: true}]">
        <div style="border: 1px solid #ccc;min-width: 700px">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :default-config="toolbarConfig"
            :mode="mode"
            :class="{'fullscreen-toolbar': isFullScreen}"
          />
          <Editor
            v-model="formData.content"
            style="overflow-y: hidden;height: 200px;"
            :default-config="editorConfig"
            :mode="mode"
            :class="{'fullscreen-editor': isFullScreen}"
            @on-created="handleCreated"
          />
        </div>
        <!--        <a-textarea v-model="formData.content" placeholder="请输入公告内容" style="height: 100px" />-->
      </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>

<!--  部门树模态框-->
  <a-modal
    width="900px"
    :visible="deptVisible"
    @cancel="deptTreeCancel"
  >
    <template #title>发送用户</template>
    <div style="display: flex;height: 520px">
      <a-card style="margin-right: 10px;width: 30%">
        <a-tree
          :data="deptTreeData"
          :field-names="{ title: 'name', key: 'id', children: 'children' }"
          style="margin-bottom: 8px; max-width: 240px"
          @select="handleClickTree"
          @check="handleCheckTree"
        >
        </a-tree>
      </a-card>
      <a-card style="flex: 1">
        <a-button type="primary" style="margin-bottom: 10px" @click="handleCheckAllUsers">全选</a-button>
        <a-table
          :data="selectedDepartmentMembers"
          :columns="columns"
          style="height: 520px">
          <template #id="{ record }">
            <a-checkbox v-model="selectedIds" :value="record.userId"> </a-checkbox>
          </template>
          <template #username="{ record }">
            {{ record.username }}
          </template>
        </a-table>
      </a-card>
    </div>
    <template #footer>
      <a-button class="editor-button" @click="deptTreeCancel" >取消</a-button>
      <a-button class="editor-button" type="primary" @click="deptTreeSubmit" >确定</a-button>
    </template>
  </a-modal>

</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { computed, defineEmits, PropType, ref, shallowRef, onBeforeUnmount, reactive, onMounted } 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'
  import { getAllDeptTree } from '@/api/dept';
  import configArcoStyleImportPlugin from '../../../../../config/plugin/arcoStyleImport';

  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 editorRef = shallowRef()
  const handleCreated = (editor: any) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
  }
  const CreateRef = ref<FormInstance>();
  const formData = ref<any>({
    ...props.prem,
  });
  const messageStore = useMessageStore();
  const isFullScreen = ref(false);
  const mode = 'default';
  const selectedIds= ref<number[]>([]);
  const toolbarConfig = { excludeKeys: ['uploadVideo', 'insertImage','insertVideo']}
  const columns = computed<any[]>(()=>[
    {
      title: '操作',
      dataIndex: 'id',
      slotName: 'id',
    },
    {
      title: '用户',
      dataIndex: 'username',
    },
  ])

  // const fieIds = ref(
  //   {
  //     userId:{
  //       label: '用戶',
  //       component: 'input',
  //       type:'text'
  //     },
  //     title:{
  //       label: '标题',
  //       component: 'input',
  //       type:'text'
  //     },
  //     remark:{
  //       label: '备注',
  //       component: 'input',
  //       type:'text'
  //     },
  //     sms:{
  //       label: '短信',
  //       component: 'switch',
  //       type:'switch'
  //     },
  //     email:{
  //       label: '邮件',
  //       component:'switch',
  //       type:'switch'
  //     },
  //     attachmentIds:{
  //       label: '附件',
  //       component: 'input',
  //       type:'text'
  //     },
  //     richEditor:{
  //       label: '内容',
  //       component: 'input',
  //       type:'text'
  //     },
  //   },
  // );
  const deptTreeData = ref([
    {
      id: '1',
      name: '总部门',
      children: [
        {
          id: '2',
          name: '部门1',
          members: [
            { id: '101', username: '成员1' },
            { id: '102', username: '成员2' }
          ]
        },
        {
          id: '3',
          name: '部门2',
          members: [
            { id: '201', username: '成员3' },
            { id: '202', username: '成员4' }
          ]
        },
        {
          id: '4',
          name: '部门3',
          members: [
            { id: '203', username: '成员5' },
            { id: '204', username: '成员6' }
          ]
        }
      ]
    }
  ]);
  const selectedDepartmentMembers: any = ref([]);
  const renderData = ref<any[]>([]);
  // 获取部门树
  const getDeptTree = async () => {
    const res = await getAllDeptTree(1);
    if (res.status === 200) {
      deptTreeData.value = res.data;
    }
  }
  // 部门树查询
  const queryDeptTree= async ()=>{
    deptVisible.value = true;
  }

  // 广度优先遍历树，获取选中的成员
  const getSelectedMembers = (treeData: any[], selectedKeys: number[]) => {
    const queue:any = [...treeData];
    const selectedMembers: any[] = [];
    while (queue.length > 0) {
      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
      const node = queue.shift()!;
      if (selectedKeys.includes(node.id)) {
        if (node.members) {
          selectedMembers.push(...node.members);
        }
      }
      if (node.children) {
        queue.push(...node.children);
      }
    }
    return selectedMembers;
  }


  // 部门树被点击
  const handleClickTree = (id: number[]) => {
    // 假设 '1' 是总部门的键
    if (id[0] === 1 && id.length === 1) {
      // 广度优先遍历树，获取所有成员
      const allMembers: any[] = [];
      const queue:any = [...deptTreeData.value];
      while (queue.length > 0) {
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        const node = queue.shift()!;
        if (node.members) {
          allMembers.push(...node.members);
        }
        if (node.children) {
          queue.push(...node.children);
        }
      }
      selectedDepartmentMembers.value = allMembers;
      renderData.value = selectedDepartmentMembers.value;
      return;
    }
    const Members = getSelectedMembers(deptTreeData.value, id);
    selectedDepartmentMembers.value = Members;
  }
  // 部门树被选中
  const handleCheckTree = (id: number[]) => {
    if (id[0] === 1 ) { // 假设 '1' 是总部门的键
      const allKeys: number[] = [];
      const traverseTree = (node: any) => {
        if (node.members) {
          node.members.forEach((member: any) => {
            allKeys.push(member.userId);
          });
        }
        if (node.children) {
          node.children.forEach((child: any) => {
            traverseTree(child);
          });
        }
      };
      deptTreeData.value.forEach((node: any) => {
        traverseTree(node);
      });
      selectedIds.value = allKeys;

    } else {
      const selectedKeys = getSelectedMembers(deptTreeData.value, id);
      selectedIds.value = selectedKeys.map(item => item.userId);
    }
  };

  // 组件被点击
  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;
  };

  // 选择所有用户
  const handleCheckAllUsers = () => {
    if(selectedIds.value.length ===0 ) {
      handleCheckTree([1]);
    } else {
      selectedIds.value = [];
    }

  };


  // 部门树模态框
  const deptTreeCancel = () => {
    deptVisible.value = false;
  };
  onMounted(async () => {
    await getDeptTree();
  });
</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>
