<template>
  <div class="mainContentBox">
    <avue-crud
      ref="crudRef"
      v-model="form"
      v-model:page="page"
      v-model:search="search"
      :data="data"
      :option="option"
      @row-save="createRow"
      @row-update="updateRow"
      @row-del="deleteRow"
      @search-change="searchChange"
      @search-reset="resetChange"
      @size-change="dataList"
      @current-change="dataList"
      @selection-change="selectionChange"
      :before-open="onCrudBeforOpen"
    >
      <template #photoLists-form>
        <MultiUpload ref="multiuploadRef" v-model="form.photoLists" />
      </template>
      <template #fileLists-form>
        <FilesUpload
          ref="filesUploadRef"
          v-model:file-name-list="photoNameList"
          v-model:src-list="photoUrlList"
          :limit="1"
          :size="3000"
          :showTip="false"
          @finished="photoChange"
        />
      </template>
      <template #menu="{ row }">
        <el-button
          v-if="row.state == '0'"
          style="color: dodgerblue"
          link
          @click="sendMsg(row)"
        >
          <el-icon>
            <Promotion />
          </el-icon>
          发送
        </el-button>
      </template>
    </avue-crud>

    <CommonTable
      ref="userTableRef"
      :multiple="true"
      tableTitle="用户"
      tableType="USERS"
      @select-multiple-sure="onSelectedFinish"
    />
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useCrud } from "@/hooks/userCrud";
import { useDictionaryStore } from "@/store";
import MultiUpload from "@/components/Upload/MultiUpload.vue";
import FilesUpload from "@/components/Upload/FilesUpload.vue";
import { sendMessage } from "@/api/message/index.ts";
import { treeList } from "@/api/user/index";
import { getMessageOrgList } from "@/api/messageOrg/index";

const userTableRef = ref(null);

const photoUrlList = ref([]);
const photoNameList = ref([]);
const deptList = ref([]); //部门列表
const getDeptList = async () => {
  let res = await treeList();
  if (res && res.code == 200) {
    deptList.value = res.data ?? []; //获取部门列表
  }
};
const photoChange = () => {
  if (photoUrlList.value.length > 0) {
    form.value.fileLists = [
      {
        name: photoNameList.value[0],
        path: photoUrlList.value[0],
      },
    ];
  } else {
    form.value.fileLists = [];
  }
};

// 数据字典相关
const { dicts } = useDictionaryStore();

// 传入一个url，后面不带/
const { form, data, option, search, page, toDeleteIds, Methords, Utils } =
  useCrud({
    src: "/api/v1/sys/message",
  });
const { dataList, createRow, updateRow, deleteRow, searchChange, resetChange } =
  Methords; //增删改查
const { selectionChange, multipleDelete } = Methords; //选中和批量删除事件

const crudRef = ref(null); //crudRef.value 获取avue-crud对象

const messageType = ref("");
const route = useRoute();

const messageOrgList = ref([]); //组织列表
const getMessageOrgsList = async () => {
  let res = await getMessageOrgList();
  if (res && res.code == 200) {
    messageOrgList.value = res.data ?? []; //获取组织列表
    console.log(messageOrgList.value, "组织列表");
  }
};

const messageChoseType = ref([
  {
    label: "系统公告",
    value: "2",
  },
  {
    label: "个人消息",
    value: "0",
  },
]);

const sendMsg = (row) => {
  sendMessage(row.id).then(() => {
    page.value.currentPage = 1;
    dataList();
  });
};

// 设置表格列或者其他自定义的option
option.value = Object.assign(option.value, {
  selection: true,
  editBtn: true,
  viewBtn: false,
  delBtn: true,
  column: [
    {
      label: "创建人",
      prop: "creator",
      search: true,
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: "消息标题",
      prop: "title",
      search: true,
      rules: [{ required: true }],
    },
    {
      label: "用户名称 ",
      prop: "receiveUsers",
      overHidden: true,
      click: ({ value, column }) => {
        userTableRef.value.startSelect();
      },
    },
    {
      label: "用户ID",
      prop: "receiveUser",
      overHidden: true,
      search: false,
      addDisplay: false,
      editDisplay: false,
      hide: true,
    },
    {
      label: "创建时间",
      prop: "created",
      addDisplay: false,
      editDisplay: false,
      width: 180,
    },

    {
      label: "已读",
      prop: "readState",
      search: false,
      type: "radio", //类型为单选框
      dicData: [
        {
          label: "否",
          value: "0",
        },
        {
          label: "是",
          value: "1",
        },
      ],
      value: "0",
      addDisplay: false,
      editDisplay: false,
      hide: true,
    },
    {
      label: "发送状态",
      prop: "state",
      search: false,
      type: "radio",
      dicData: [
        {
          label: "暂存",
          value: "0",
        },
        {
          label: "直接发送",
          value: "1",
        },
      ],
      value: "1",
    },
    {
      label: "msgId",
      prop: "msgId",
      addDisplay: false,
      editDisplay: false,
      value: "10",
      hide: true,
    },
    {
      label: "发送部门",
      prop: "deptIds",
      overHidden: true,
      type: "tree",
      dicData: deptList, // 使用树形结构数据
      props: {
        label: "deptName", // 显示的字段
        value: "id", // 传递给后端的字段
        children: "children", // 子节点字段
      },
      multiple: true, // 支持多选
      showCheckbox: true, // 显示复选框
      search: true,
      valueformat: "array", // 确保值是数组格式
      // nodeKey: "id",
      // formatter: (row) => {
      //   if (!row.deptIds) return "";
      //   return row.deptIds.map(id => {
      //     const dept = findDeptById(deptList.value, id);
      //     return dept ? dept.deptName : id;
      //   }).join(", ");
      // }
    },
    {
      label: "消息组织",
      prop: "messageOrgIds",
      type: "select",
      dicData: messageOrgList, // 组织列表
      overHidden: true,
      props: {
        label: "messageOrgName",
        value: "id",
      },
      multiple: true, // 支持多选
    },
    {
      label: "消息内容",
      prop: "content",
      search: true,
      type: "textarea",
      overHidden: true,
      required: true,
      rules: [{ required: true }],
    },
    {
      label: "消息类型",
      prop: "type",
      search: false,
      type: "radio",
      dicData: messageChoseType.value,
      value: "0",
    },

    {
      label: "图片列表",
      prop: "photoLists",
      type: "array",
      span: 24,
      hide: true,
    },
    {
      label: "文件列表",
      prop: "fileLists",
      type: "array",
      span: 24,
      hide: true,
    },
  ],
});

// const findDeptById = (nodes, id) => {
//   // 递归查找部门
//     for (const node of nodes) {
//       if (node.id === id) return node;
//       if (node.children) {
//         const found = findDeptById(node.children, id);
//         if (found) return found;
//       }
//     }
//     return null;
// };
const onSelectedFinish = (selectedRowIds) => {
  form.value.receiveUsers = selectedRowIds;
  console.log(selectedRowIds, form.value);
};

onMounted(() => {
  search.value.messageId = "10";
  search.value.type = messageType.value = route.params.type;

  option.value.column.forEach((item) => {
    if (item.prop === "type") {
      item.value = messageType.value;
      item.dicData = messageChoseType.value.filter(
        (item) => item.value === messageType.value
      );
    }
    if (item.prop === "receiveUsers") {
      item.addDisplay = messageType.value === "0";
      item.editDisplay = messageType.value === "0";
    }
    if (item.prop === "deptIds") {
      item.viewDisplay = false;
    }
  });
  dataList();
  getDeptList();
  getMessageOrgsList();
});

const filesUploadRef = ref();
const multiuploadRef = ref();
const onCrudBeforOpen = (done, type) => {
  done();
  if (type === "edit") {
    nextTick(() => {
      multiuploadRef.value &&
        multiuploadRef.value.initList(form.value.photoLists);
      filesUploadRef.value &&
        filesUploadRef.value.setFileList(form.value.fileLists);
    });
  }
};
</script>
