<template>
  <div>
    <div style="margin-right: 20px">
      <div style="text-align: center; margin-bottom: 25px">收件箱</div>

      <!-- <div style="margin-top: 10px">
      <el-alert title="未使用任何数据" type="warning" show-icon />
    </div> -->
      <div>
        <el-form
          style="width: 1400px"
          :model="queryParams1"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="邮件标题:" prop="mainTitle">
            <el-input
              v-model="queryParams1.mainTitle"
              placeholder="请输入邮件标题"
              clearable
              style="width: 10vw"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="邮件状态:" prop="isRead">
            <el-select
              v-model="queryParams1.isRead"
              placeholder="用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in is_read"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="收件时间:" style="width: 308px">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleQuery"
              ><el-icon><Search /></el-icon>搜索</el-button
            >
            <el-button size="mini" @click="resetQuery"
              ><el-icon><RefreshRight /></el-icon>重置</el-button
            >
          </el-form-item></el-form
        >
      </div>
      <div style="display: flex">
        <el-button
          @click="unreadList"
          link
          style="font-size: 15px; color: #409eff"
        >
          有 {{ unreadNum }} 封未读
        </el-button>

        <el-button @click="setAsRead" type="primary"
          ><div style="font-size: 14px">全部设为已读</div>
        </el-button>

        <el-button @click="delEmail()" size="mini" type="danger">
          删除
        </el-button>
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="inboxList"
        ></right-toolbar>
      </div>
      <div style="margin-top: 10px">
        <div style="margin-top: 10px; overflow: auto; height: 540px">
          <el-table
            v-loading="loading"
            ref="multipleTableRef"
            :data="tableData"
            style="width: 100%"
            @selection-change="handleSelectionChange1"
          >
            <el-table-column width="55" type="selection" align="center" />
            <el-table-column align="center" prop="isRead" width="40">
              <template #default="scope">
                <el-icon v-if="scope.row.isRead == 'Y'"></el-icon>
                <el-icon v-else
                  ><Message color="#f8ac59" size="25px"
                /></el-icon>
              </template>
              <!-- <template #default="scope">
                <dict-tag :options="is_read" :value="scope.row.isRead" />
              </template> -->
            </el-table-column>
            <el-table-column
              prop="mainTitle"
              label="邮件标题"
              width="510"
              show-overflow-tooltip
            >
              <template #default="scope">
                <el-button size="mini" type="text" @click="viewEmail(scope)">
                  <div>
                    <div
                      style="display: inline-block"
                      v-if="scope.row.mailState !== null"
                    >
                      <el-icon
                        :style="{
                          color: scope.row.mailState === '1' ? 'white' : 'red',
                        }"
                        ><Bell
                      /></el-icon>
                    </div>
                    <div style="display: inline-block; margin-left: 10px">
                      {{ scope.row.mainTitle }}
                    </div>
                  </div></el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="sendUserName"
              align="center"
              label="发件人"
            />

            <el-table-column align="center" prop="sendTime" label="收件时间">
              <template #default="scope">
                {{ parseTime(scope.row.sendTime, "{y}-{m}-{d} {h}:{i}") }}
              </template>
            </el-table-column>

            <!-- <el-table-column align="center" label="操作">
              <template #default="scope">
                <el-button
                  @click="viewEmail(scope)"
                  text="primary"
                  type="primary"
                  size="mini"
                >
                  <el-icon style="margin-left: 5px"><View /></el-icon> 查看
                </el-button>
                <el-button
                  @click="forwardEmail(scope)"
                  size="mini"
                  type="success"
                  text="success"
                >
                  <el-icon><RefreshRight /></el-icon> 转发
                </el-button>
                <el-button
                  @click="delEmail(scope.row.mailId)"
                  size="mini"
                  type="danger"
                  text="danger"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
        <div style="float: right; margin-top: 10px">
          <el-pagination
            v-model:current-page="queryParams1.pageNum"
            v-model:page-size="queryParams1.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange1"
            @current-change="handleCurrentChange1"
          />
        </div>
      </div>
      <el-dialog
        v-model="dialogVisible1"
        title="查看邮件"
        width="45%"
        :before-close="handleClose"
      >
        <div style="border-bottom: 1px solid #e8e8e8; padding-bottom: 15px">
          <div style="font-size: 16px">
            标题：<span style="font-weight: 700; font-size: 15px">{{
              mainTitle
            }}</span>
          </div>

          <div style="font-size: 15px; margin-top: 12px">
            发件人：{{ sendUserName }}
          </div>
          <div style="font-size: 15px; margin-top: 12px">
            发件时间： {{ parseTime(sendTime, "{y}-{m}-{d} {h}:{i}") }}
          </div>
          <div></div>
        </div>
        <div style="height: 520px; overflow: auto">
          <div style="padding: 10px 0" v-html="mailContent"></div>
          <div v-for="image in getImagesFromData(mailContent)">
            <el-image
              :fit="contain"
              :src="image.src"
              :alt="image.alt"
              :width="image.width"
              :height="image.height"
            />
          </div>
          <div v-if="this.files !== []">
            <div v-for="item in files" :key="item" style="margin-top: 0px">
              <el-icon style="color: #1b6ef3; font-size: 26px; padding-top: 0px"
                ><Paperclip style="padding-top: 10px" /></el-icon
              ><a
                style="color: #1b6ef3; font-size: 15px"
                target="_blank"
                :href="item.url"
                >{{ item.name }}</a
              >
            </div>
          </div>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="recover"> 回复 </el-button>
            <el-button type="primary" @click="forwardEmail"> 转发 </el-button>
            <el-button @click="dialogVisible1 = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref } from "vue";
import { ElTable } from "element-plus";
import { getToken } from "@/utils/auth";
import Editor1 from "../../../../src/components/Editor1.vue";
import { ArrowDown } from "@element-plus/icons-vue";
import {
  inboxList,
  setAsRead,
  unread,
  deleteBoxMail,
  unreadList,
  detail,
} from "../../../api/email/inbox";
import {
  changeUserStatus,
  listUser,
  resetUserPwd,
  delUser,
  getUser,
  updateUser,
  addUser,
  deptTreeSelect,
} from "@/api/system/user";
import { useDict } from "@/utils/dict";
export default {
  props: ["showWrite"],
  // components: {
  //   write,
  //   Editor1,
  // },

  created() {
    this.inboxList();
    this.unread();
    const deptOptions = localStorage.getItem("deptOptions");
    // //console.log("deptOptions", deptOptions);
    if (deptOptions) {
      this.currentNodeKey = JSON.parse(deptOptions).id;
      this.expandedKeys = [JSON.parse(deptOptions).id];
    }
  },
  data() {
    return {
      dateRange: [],
      getRowKeys(row) {
        // //console.log("rowrow", row.userId);
        return row.userId;
      },
      upload: {
        headers: { Authorization: "Bearer " + getToken() },
        url: import.meta.env.VITE_APP_BASE_API + "/system/file/fileupload",
      },
      ids: [],
      idss: [],
      showSearch: true,
      showWrite: false,
      dialogVisible: false,
      dialogVisible1: false,
      is_read: useDict("is_read").is_read,
      queryParams1: {
        pageNum: 1,
        pageSize: 10,
        mainTitle: undefined,
      },
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      deptOptions: [],

      ruleForm: {
        mailUserIds: [],
        isRead: "N",
        isDel: "N",
        mailType: "2",
        sendTime: "",
        files: [],
        // sendUserName: [],
      },
      loading: false,
      small: false,
      files: [],
      selection: [],
      nickName: [],
      background: false,
      disabled: false,
      tableData: [],
      unreadNum: "",
      total: 0,
      ids: [],
      delids: [],
      sendTime: null,
      sendUserName: null,
      mainTitle: "",
      mailContent: "",
      mailId: null,
      mailId1: null,
      mailId3: null,
    };
  },

  methods: {
    handleQuery() {
      this.queryParams1.pageNum = 1;
      this.inboxList();
    },
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange1(selection) {
      //console.log("selection", selection);
      this.delids = selection.map((item) => item.mailId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      //console.log("this.ids", this.delids);
    },
    //获取token
    getToken() {
      return getToken();
    },
    handleSelect() {
      //console.log("yes");
      this.getList();
      this.getDeptTree();
      const deptOptions = localStorage.getItem("deptOptions");
      //console.log("deptOptions", deptOptions);
      if (deptOptions) {
        this.currentNodeKey = JSON.parse(deptOptions).id;
        this.expandedKeys = [JSON.parse(deptOptions).id];
      }
      this.dialogVisible = true;
    },
    submitEmail1() {
      this.$emit("updateUnreadAndDrafts");
    },
    //回复
    async recover() {
      this.dialogVisible1 = false;
      this.mailId3 = this.mailId;
      // this.showWrite = true;
      // let { data } = await detail(this.mailId);
      // this.ruleForm.sendTime = data.sendTime;
      // this.nickName = data.sendUserName;
      // this.ruleForm.mailUserIds = data.mailUserIds;
      // this.ruleForm.mailContent =
      //   data.mailContent + "\n------------------ 原始邮件 ------------------";
      // this.ruleForm.mainTitle = "回复：" + data.mainTitle;
      // this.files = data.files == null ? [] : data.files;
      // this.ruleForm.mailStatus = data.mailStatus;
      this.$emit("selectPage", 0, this.mailId3);
    },
    //转发
    async forwardEmail() {
      this.dialogVisible1 = false;
      // this.showWrite = true;
      this.mailId1 = this.mailId;
      // let { data } = await detail(scope.row.mailId);
      // this.ruleForm.sendTime = data.sendTime;
      // this.ruleForm.sendUserName = data.sendUserName;
      // this.ruleForm.mailUserIds = data.mailUserIds;
      // this.ruleForm.mailContent =
      //   data.mailContent + "\n------------------ 原始邮件 ------------------";
      // this.ruleForm.mainTitle = "转发：" + data.mainTitle;
      // this.files = data.files;
      // this.ruleForm.mailStatus = data.mailStatus;
      this.$emit("selectPage1", 0, this.mailId1, 1);
    },
    //发布
    submitEmail() {
      this.currentTime();
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          for (var i = 0; i < this.files.length; i++) {
            //console.log("111", this.files[i].response.data);
            this.ruleForm.files.push(this.files[i].response.data);
          }
          mail(this.ruleForm).then((response) => {
            //console.log("发布", response);
            this.$modal.msgSuccess("发送成功");
            this.reset();
            this.$parent.allbox();
          });
        }
      });
    },
    //存为草稿
    saveEmail() {
      this.currentTime();
      this.$refs["ruleFormRef"].validate((valid) => {
        if (valid) {
          for (var i = 0; i < this.files.length; i++) {
            //console.log(this.files[i].response.data);
            this.ruleForm.files.push(this.files[i].response.data);
          }
          drafts(this.ruleForm).then((response) => {
            //console.log("存为草稿", response);
            this.$modal.msgSuccess("存为草稿成功");
            this.reset();
          });
        }
      });
    },
    //重置
    reset() {
      this.ruleForm = {
        name: [],
        mailUserIds: [],
        mainTitle: "",
        mailContent: "",
        files: null,
        mailStatus: null,
        filePath: null,
      };
      this.mailId = null;
      this.ids = [];
      this.idss = [];
      this.files = [];
      this.nickName = [];
      this.selection = [];
      this.getList();
    },
    // 获取当前时间
    currentTime() {
      var date = new Date();
      //console.log("date", date);
      this.ruleForm.sendTime = date;
    },
    // // 数据
    async getList() {
      this.loading = true;
      //console.log(this.addDateRange(this.queryParams, this.dateRange));
      await listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (res) => {
          this.loading = false;
          this.userList = res.rows;
          this.total = res.total;
        }
      );
      this.selection = [];
    },
    /** * 表格单行返回是否可以勾选 */
    getSelectable(row) {
      return row.status !== "REJECT";
    },
    // /** 节点单击事件 */
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },

    // // 多选框选中数据
    handleSelectionChange(selection) {
      //console.log("selection", selection);
      this.selection = selection;
      this.ids = [];
      this.ids.push(
        this.selection.map((item) => ({
          userId: item.userId,
          nickName: item.nickName,
        }))
      );
      //console.log("ids", this.ids);
      this.idss = this.ids[0];
      //console.log("idss", this.idss);
      this.single = this.selection.length !== 1;
      this.multiple = !this.selection.length;

      this.selection = [];
    },
    //确认收件人
    submitUserList() {
      this.nickName = [];
      for (let i = 0; i < this.idss.length; i++) {
        let item = this.idss[i];
        //console.log("item", item);

        this.nickName.push(item.nickName);
        this.ruleForm.mailUserIds.push(item.userId + "");
        //console.log("this.ruleForm.mailUserIds", this.ruleForm.mailUserIds);
      }
      // this.ruleForm.name = this.ids;
      this.dialogVisible = false;
    },
    getImagesFromData(data) {
      // 在这里解析数据，提取图片信息并返回一个包含图片相关属性的数组
      // 例如，假设数据中的图片信息是以<img>标签的形式呈现的：
      const imagePattern =
        /<img\s*src="([^"]+)"\s*alt="([^"]+)"\s*width="(\d+)"\s*height="(\d+)"\s*\/?>/g;
      const images = [];
      let match;
      while ((match = imagePattern.exec(data)) !== null) {
        const src = match[1];
        const alt = match[2];
        const width = parseInt(match[3], 10);
        const height = parseInt(match[4], 10);
        images.push({ src, alt, width, height });
      }
      return images;
    },
    async viewEmail(scope) {
      let { data } = await detail(scope.row.mailId);
      this.dialogVisible1 = true;
      //console.log("data", data);
      this.sendTime = data.sendTime;
      this.sendUserName = data.sendUserName;
      this.mailContent = data.mailContent;
      this.mainTitle = data.mainTitle;
      this.mailId = data.mailId;
      this.files = data.files;
      this.inboxList();
      this.unread();
      this.$nextTick(() => {
        this.$emit("updateUnreadAndDrafts");
      });
    },
    //未读列表
    async unreadList() {
      let { rows } = await unreadList();
      this.tableData = rows;
      this.$nextTick(() => {
        this.$emit("updateUnreadAndDrafts");
      });
    },
    //删除邮件
    async delEmail() {
      const ids = this.delids;
      //console.log("ids", ids);
      if (ids.length == 0) {
        this.$modal.msgError("请选择删除邮件");
      } else {
        this.$modal
          .confirm("是否删除已勾选邮件 ?")
          .then(function () {
            return deleteBoxMail(ids);
          })
          .then(() => {
            this.$modal.msgSuccess("删除邮件成功");
            this.inboxList();
            this.unread();
            this.$emit("updateUnreadAndDrafts");
          })
          .catch(() => {});
      }
    },
    //未读数量
    async unread() {
      const unreadNum = await unread();
      this.unreadNum = unreadNum;
      this.$nextTick(() => {
        this.$emit("updateUnreadAndDrafts");
      });
    },
    //全部设为已读
    async setAsRead() {
      let { code } = await setAsRead();
      if (code == 200) {
        this.$modal.msgSuccess("设置已读成功");
        this.inboxList();
        this.unread();
        this.$emit("updateUnreadAndDrafts");
      }
    },
    //收件箱数据
    async inboxList() {
      this.loading = true;
      let { rows, total } = await inboxList(
        this.addDateRange(this.queryParams1, this.dateRange)
      );
      this.tableData = rows;
      this.total = total;
      this.loading = false;
    },

    handleSizeChange1(newPage) {
      //console.log("newPage", newPage);
      this.queryParams1.pageSize = newPage;
      this.inboxList();
    },
    handleCurrentChange1(val) {
      //console.log(val);
      this.queryParams1.pageNum = val;
      this.inboxList();
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep img {
  max-width: 790px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  // color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
::v-deep .el-dialog__body {
  padding-top: 15px;
  border-top: 1px solid #e8e8e8;
}
</style>
