<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
        <div class="search">
          <div class="sl">
            <el-form-item label="消息内容" prop="content">
              <el-input
                v-model="queryParams.content"
                placeholder="请输入消息内容"
                clearable
                style="width: 240px"
                @clear="handleQuery"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="消息类型" prop="businessType">
              <el-select v-model="queryParams.businessType" placeholder="请选择消息类型" clearable @change="handleQuery">
                <el-option
                  v-for="dict in dict.type.msg_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="states">
              <el-select v-model="queryParams.states" placeholder="请选择状态" clearable @change="handleQuery">
                <el-option
                  v-for="dict in dict.type.msg_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="sr">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </el-card>
    <el-card class="lrtt">
      <div class="rt">
        <div class="operate">
          <el-button type="primary" v-if="tableList && tableList.length > 0" @click="setAllMarkedRead" icon="el-icon-check">全部标记已读</el-button>
        </div><!--operate 操作按钮-->
        <el-table v-loading="loading" :data="tableList">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="消息内容" prop="content" min-width="120">
            <template  v-slot="{ row }">
              <el-link target="_blank" @click="handleDetail(row)">
                {{ row.content }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column label="消息类型" align="center" prop="businessType" width="80px">
            <template  v-slot="{ row }">
              <template v-for="dict in dict.type.msg_type">
                <!-- {{ dict }} -->
                <el-tag :type="dict.raw.listClass" v-if="row.businessType == dict.value" :key="dict.value">{{ dict.label }}</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="接收时间" prop="createTime" :show-overflow-tooltip="true" width="160px"/>
          <el-table-column label="消息状态" prop="states" align="center" :show-overflow-tooltip="true" width="80px" >
            <template  v-slot="{ row }">
              <template v-for="dict in dict.type.msg_status">
                <!-- {{ dict }} -->
                <el-tag :type="dict.raw.listClass" v-if="row.states == dict.value" :key="dict.value">{{ dict.label }}</el-tag>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160px" fixed="right">
            <template v-slot="{ row }">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                v-if="row.states == '1'"
                @click="markRead(row)"
              >标记已读</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>


    <!-- 工具详情对话框 -->
    <el-drawer :visible.sync="detailDrawerOpen" :modal-append-to-body="false" :show-close="false" :wrapperClosable="false"
               size="80%" class="no-padding" :close-on-press-escape="false"	@close="handleCloseDetail()">
      <template #title>
        <span>{{toolTitle}}</span>
        <div class="drawer-head-btn">
          <el-button icon="el-icon-close" @click="detailDrawerOpen = false">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
      </template>
      <template v-if="detailOpen">
        <tool-detail ref="toolDetailRef" :toolDetail="toolDetail" :isDownload="false" :isComment="false"/>
      </template>
    </el-drawer><!--el-drawer 详情-抽屉-->



    <!--文档详情-->
    <el-drawer :visible.sync="detailDocOpen"
               :modal-append-to-body="false" :show-close="false" :close-on-press-escape="false"
               size="75%">
      <template #title>
        <span class="title">{{docTitle}}</span>
        <div class="drawer-head-btn">
          <el-button icon="el-icon-close" @click="docCancel()">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
      </template>
      <doc-detail ref="editDocumentRef" @submit="editDocumentSubmit" :isDownload="false" :isComment="false"/>
    </el-drawer>

  </div>
</template>

<script>
import { listMessage, updateMessage,allMarkedRead } from "@/api/message/message"
import { deptTreeSelect } from "@/api/system/user";
import docDetail from "@/views/document/detail";
import toolDetail from "@/views/tool/toolDetail";
import {  getUserMsgCount } from "@/api/message/message"
import store from '@/store'

export default {
  name: "Document",
  dicts: ['msg_status', 'msg_type'],
  components: { docDetail, toolDetail},

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 弹出层标题
      title: "",
      viewDialogTitle: "",
      viewDialogOpen: false,
      open: false,
      // 日期范围
      dateRange: [],
      previewUrl: '',
      progress: 0,
      fileList: [],
      // websocket: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        content: '',
        states: '',
        businessType: '',
      },
      //工具
      detailDrawerOpen: false,
      toolTitle:'',
      detailOpen: false,
      toolDetail: {},
      //文档
      docTitle: '',
      detailDocOpen: false,
      docTipAddOrEdit: null,
      docDetailDisable: true,
    };
  },
  created() {
    if(this.$route.query.states){
      this.queryParams.states = this.$route.query.states
    }
    this.getList();
    this.getDeptTree();

  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    getList() {
      this.loading = true
      this.$set(this.queryParams,"receiverId", this.$store.getters.userId)
      listMessage(this.queryParams).then(response => {
        this.total = response?.total
        this.tableList = response?.rows || []
        this.loading = false
      }).catch(() => { this.loading = false });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
     /** 重置按钮操作 */
     resetQuery() {
      this.tableList = []
      this.resetForm("queryForm")
       this.queryParams.states = null
      this.handleQuery()
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.toolRespDept = data.id;
      this.handleQuery();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /**
     * 标记已读：id为null时表示标记全部已读
     * @param id
     */
    markRead(row) {
      let self = this
      let formData = JSON.parse(JSON.stringify(row))
      self.$set(formData, "states", 2)
      updateMessage(formData).then(response => {
        self.$modal.msgSuccess(response?.msg || '操作成功')
        store.dispatch('GetUserMsgCount').then(() => { })
        self.getList();
      }).catch((err) => {console.error(err)});
      /* self.$confirm('确认标记已读吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      }).catch((err) => {console.error(err)}); */
    },

    /**
     * 标记已读：id为null时表示标记全部已读
     * @param id
     */
    setAllMarkedRead() {
      let self = this
      self.$confirm('确认全部标记已读吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let formData = {
          "states": 2
        }
        allMarkedRead(formData).then(response => {
          self.$modal.msgSuccess(response?.msg || '操作成功')
          store.dispatch('GetUserMsgCount').then(() => { })
          self.getList();
        })
      }).catch((err) => {console.error(err)});
    },
    /** 查看详情 **/
    handleDetail(row){
      if(row.businessType == 'tool'){
        this.detailDrawerOpen = true
        this.detailOpen = true
        this.toolDetail = {toolId: row.businessId}
        this.toolTitle = '工具详情'
      }else if(row.businessType == 'doc'){
        this.docTitle="文档详情"
        this.docTipAddOrEdit = 'detail'
        this.docDetailDisable=false
        this.detailDocOpen = true
        this.$nextTick(()=>{
          this.$refs.editDocumentRef.editInit(row.businessId, "detail");
        })
      }
    },
    /** 关闭详情 **/
    handleCloseDetail(){
      this.detailDrawerOpen = false;
      this.detailOpen = false;
      this.$refs.toolDetailRef.$destroy(); // 销毁组件
      this.$nextTick(() => {
        this.$refs.toolDetailRef = null; // 清空引用
      });
    },
    docCancel(){
      this.$refs.editDocumentRef.resetForm();
      this.detailDocOpen = false
    },
    editDocumentSubmit: function() {
      this.detailDocOpen = false;
    },
  }
};
</script>

