<template>
  <div>
    <div
      style="padding-left: 20px; display: flex; align-items: center"
      v-loading="btnLoading"
    >
      <el-icon @click="handleRefresh" style="cursor: pointer">
        <Refresh />
      </el-icon>
      <div class="vertical-line"></div>
      <div>
        <el-checkbox
          v-model="isCheckAll"
          label="全选"
          size="default"
          @change="handleChangeCheckAll"
        />
      </div>
      <div style="color: #666666">
        <span
          >（共 {{ tableData.pagination.total }} 封，其中<span
            style="color: #39c55a"
          >
            未读邮件 </span
          >{{ unReadCount }} 封）</span
        >
      </div>
      <el-button
        @click="handleSetAllRead"
        :disabled="selectData.length === 0"
        style="margin-left: 10px"
        >全部标为已读</el-button
      >
      <el-select
        v-model="selectTag"
        placeholder="标记为"
        style="margin: 0 10px; width: 120px"
        :disabled="selectData.length === 0"
        @change="handleSetTag"
      >
        <el-option
          v-for="item in tagData"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-tree-select
        v-model="selectFolder"
        :data="myFolderTreeData"
        :disabled="selectData.length === 0"
        placeholder="移动到"
        style="margin-right: 10px; width: 120px"
        check-strictly
        :render-after-expand="false"
        @change="handleSetFolder"
      />
      <el-button @click="handleDeleteAll" :disabled="selectData.length === 0"
        >删除</el-button
      >
    </div>
    <div style="padding: 10px 15px; width: 100%">
      <el-table
        :data="tableData.data"
        style="width: 100%"
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column label=" " width="40" align="center">
          <template #default="{ row, $index }">
            <div>
              <el-checkbox
                v-model="row.isCheck"
                label=""
                size="default"
                @change="handleChangeCheck"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="70">
          <template #default="{ row, $index }">
            <div style="cursor: pointer" @click="handleRowClick(row, $index)">
              <span v-if="row.flags && !row.flags.includes('6')">
                <img
                  src="@/assets/images/mail/message.png"
                  alt=""
                  title="未读"
                  class="messageImg"
                />
              </span>
              <span
                v-if="
                  row.flags !== undefined &&
                  row.flags !== null &&
                  row.flags === ''
                "
              >
                <img
                  src="@/assets/images/mail/message.png"
                  alt=""
                  title="未读"
                  class="messageImg"
                />
              </span>
              <span
                v-if="
                  row.flags &&
                  row.flags.includes('6') &&
                  row.flags.includes('1')
                "
              >
                <img
                  src="@/assets/images/mail/replied.png"
                  alt=""
                  title="已回复"
                  class="messageImg"
                />
              </span>
              <span v-if="row.flags && row.flags.includes('6')">
                <img
                  src="@/assets/images/mail/message-open.png"
                  alt=""
                  title="已读"
                  class="messageImg"
                />
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fromPersonalName" label="发件人" width="150">
          <template #default="{ row, $index }">
            <div class="contentClass" @click="handleRowClick(row, $index)">
              {{ row.fromPersonalName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fromEmail" label="发件人地址" width="210">
          <template #default="{ row, $index }">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="row.fromEmail"
              placement="top"
            >
              <div class="contentClass" @click="handleRowClick(row, $index)">
                {{ row.fromEmail }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="subject" label="主题">
          <template #default="{ row, $index }">
            <div class="contentClass" @click="handleRowClick(row, $index)">
              {{ row.subject }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="sendDate" label="时间" width="160">
          <template #default="{ row, $index }">
            <div style="cursor: pointer" @click="handleRowClick(row, $index)">
              {{ row.sendDate }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="tableData.pagination.pageNum"
        v-model:page-size="tableData.pagination.pageSize"
        :page-sizes="[15, 30, 50, 100]"
        layout="sizes, prev, pager, next"
        :total="tableData.pagination.total"
        prev-text="上一页"
        next-text="下一页"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<script setup>
import byTable from "@/components/byTable/index";
import useMailStore from "@/store/modules/mail";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const mailStore = useMailStore();
let loading = ref(false);
const tableHeight = ref(0);
const getTableHeight = () => {
  tableHeight.value = window.innerHeight - 280;
};
getTableHeight();
window.addEventListener("resize", () => {
  getTableHeight();
});
const tableData = reactive({
  data: [],
  pagination: {
    pageNum: 1,
    pageSize: 15,
    total: 0,
  },
});
const unReadCount = computed(() => mailStore.currentMenu.unReadCount);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "状态",
        slot: "icon",
        width: 70,
      },
    },
    {
      attrs: {
        label: "发件人",
        prop: "fromPersonalName",
      },
    },
    {
      attrs: {
        label: "发件人地址",
        prop: "fromEmail",
      },
    },
    {
      attrs: {
        label: "主题",
        prop: "subject",
      },
    },
    {
      attrs: {
        label: "时间",
        prop: "sendDate",
      },
    },
  ];
});

const getList = () => {
  if (mailStore.currentMenu.listPageType === "10") {
    loading.value = true;
    proxy
      .post("/mailService/getMessagePage", {
        ...mailStore.currentMenu,
        ...tableData.pagination,
      })
      .then((res) => {
        tableData.data = res.rows.map((x) => ({ ...x, isCheck: false }));
        mailStore.mailDataList = res.rows.map((x) => ({
          ...x,
          isCheck: false,
        }));
        tableData.pagination.total = res.total;
        loading.value = false;
      });
  } else if (mailStore.currentMenu.listPageType === "20") {
    loading.value = true;
    proxy
      .post("/myFolderMessage/page", {
        myFolderId: mailStore.currentMenu.folderId,
        type: mailStore.selectMail.type,
        ...tableData.pagination,
      })
      .then((res) => {
        tableData.data = res.rows.map((x) => ({
          ...x,
          isCheck: false,
        }));
        mailStore.mailDataList = res.rows.map((x) => ({
          ...x,
          isCheck: false,
        }));
        tableData.pagination.total = res.total;
        loading.value = false;
      });
  } else if (mailStore.currentMenu.listPageType === "30") {
    loading.value = true;
    proxy
      .post("/myTagMessage/page", {
        myTagId: mailStore.currentMenu.folderId,
        type: mailStore.selectMail.type,
        ...tableData.pagination,
      })
      .then((res) => {
        tableData.data = res.rows.map((x) => ({
          ...x,
          isCheck: false,
        }));
        mailStore.mailDataList = res.rows.map((x) => ({
          ...x,
          isCheck: false,
        }));
        tableData.pagination.total = res.total;
        loading.value = false;
      });
  }
};

const handleRefresh = () => {
  tableData.pagination = {
    pageNum: 1,
    pageSize: 15,
  };
  // getList();
};

const handleRowClick = (row, index) => {
  mailStore.currentMailIndex = index;
  const menu = {
    title: row.subject.slice(0, 4) + "...",
    type: mailStore.selectMail.type,
    messageId: row.id,
    id: "detail" + "," + row.id,
    time: row.sendDate,
    subject: row.subject,
    row: { ...row },
  };
  const menuItem = mailStore.mailMenuList.find((x) => x.id === menu.id);
  if (menuItem === undefined) {
    mailStore.mailMenuList.push(menu);
  }
  mailStore.currentMenu = menu;
  mailStore.currentId = menu.id;
};

const init = () => {
  getList();
};

const handleCurrentChange = (val) => {
  tableData.pagination.pageNum = val;
  getList();
};

const handleSizeChange = (val) => {
  tableData.pagination.pageSize = val;
  getList();
};
const myFolderTreeData = ref([]);
const tagData = ref([]);

const handleTreeData = (arr) => {
  for (let i = 0; i < arr.length; i++) {
    const e = arr[i];
    e.value = e.id;
    if (e.children && e.children.length > 0) {
      e.children = handleTreeData(e.children);
    }
  }
  return arr;
};

const getOtherData = () => {
  setTimeout(() => {
    proxy
      .post("/myFolder/tree", { mailboxId: mailStore.selectMail.id })
      .then((res) => {
        myFolderTreeData.value = handleTreeData(res);
      });
  }, 1000);

  setTimeout(() => {
    proxy
      .post("/myTag/page", {
        pageNum: 1,
        pageSize: 9999,
        id: useUserStore().user.userId,
      })
      .then((res) => {
        tagData.value = res.rows;
      });
  }, 1000);
};
getOtherData();
const isCheckAll = ref(false);
const selectTag = ref("");
const selectFolder = ref("");
const selectData = ref([]);
const handleChangeCheck = () => {
  selectData.value = tableData.data.filter((x) => x.isCheck === true);
  if (selectData.value.length === tableData.data.length) {
    isCheckAll.value = true;
  }
};

const handleChangeCheckAll = () => {
  tableData.data.forEach((x) => {
    x.isCheck = isCheckAll.value;
  });
  if (isCheckAll.value) {
    selectData.value = tableData.data;
  } else {
    selectData.value = [];
  }
};
const btnLoading = ref(false);
const handleSetAllRead = () => {
  btnLoading.value = true;
  const uidList = selectData.value.map((x) => x.id);
  const data = {
    folderName: mailStore.currentMenu.oldName,
    uidList,
    mailboxId: mailStore.selectMail.id,
    type: mailStore.selectMail.type,
  };
  proxy.post("/mailService/setSeen", data).then(
    (res) => {
      ElMessage({
        message: `操作成功！`,
        type: "success",
      });
      btnLoading.value = false;
    },
    (err) => {
      btnLoading.value = false;
    }
  );
};

const handleSetTag = (val) => {
  if (!val) return;
  btnLoading.value = true;
  const messageIdList = selectData.value.map((x) => x.id);
  const data = {
    myTagId: val,
    messageIdList,
  };
  proxy.post("/myTagMessage/addBath", data).then(
    (res) => {
      ElMessage({
        message: `操作成功！`,
        type: "success",
      });
      selectTag.value = "";
      btnLoading.value = false;
    },
    (err) => {
      btnLoading.value = false;
    }
  );
};

const handleSetFolder = (val) => {
  if (!val) return;
  btnLoading.value = true;
  const messageIdList = selectData.value.map((x) => x.id);
  const data = {
    myFolderId: val,
    messageIdList,
  };
  proxy.post("/myFolderMessage/addBath", data).then(
    (res) => {
      ElMessage({
        message: `操作成功！`,
        type: "success",
      });
      selectFolder.value = "";
      btnLoading.value = false;
    },
    (err) => {
      btnLoading.value = false;
    }
  );
};

const handleDeleteAll = () => {
  ElMessageBox.confirm(`此操作将删除选中的邮件, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    btnLoading.value = true;
    const idList = selectData.value.map((x) => x.id);
    const data = {
      type: mailStore.selectMail.type,
      idList,
    };
    proxy.post("/mailService/deleteBatchMail", data).then(
      (res) => {
        ElMessage({
          message: `操作成功！`,
          type: "success",
        });
        btnLoading.value = false;
        selectData.value = [];
        getList();
      },
      (err) => {
        btnLoading.value = false;
      }
    );
  });
};

defineExpose({
  initFn: init,
});
</script>

<style lang="scss" scoped>
// * {
//   font-size: 12px;
// }
.messageImg {
  width: 18px;
  height: 18px;
  transform: translateY(5px);
}
.el-pagination {
  padding-left: 30vw;
}
.contentClass {
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.vertical-line {
  width: 2px;
  height: 14px;
  background: #dddddd;
  margin: 0 10px;
}
</style>