<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="消息类型" prop="messageType">
        <el-select v-model="queryParams.messageType" placeholder="请选择消息类型" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_message_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="消息级别" prop="messageLevel">
        <el-select v-model="queryParams.messageLevel" placeholder="请选择消息级别" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_message_level"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

<!--      <el-form-item label="接收人" prop="recipientNick">
        <el-input
            v-model="queryParams.recipientNick"
            placeholder="请输入接收人"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>-->

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_message_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
        >测试</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:message:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:message:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="消息类型" align="center" prop="messageType">
        <template #default="scope">
          <dict-tag :options="sys_message_type" :value="scope.row.messageType"/>
        </template>
      </el-table-column>
      <el-table-column label="消息级别" align="center" prop="messageLevel">
        <template #default="scope">
          <dict-tag :options="sys_message_level" :value="scope.row.messageLevel"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="messageTitle" />
      <el-table-column label="内容" align="center" prop="messageContent" />
      <el-table-column label="发送时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_message_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              type="primary"
              link
              icon="View"
              @click="handleView(scope.row)"
              v-hasPermi="['system:message:query']"
          >查看</el-button>
<!--          <el-button
              type="primary"
              link
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:message:edit']"
          >修改</el-button>-->
          <el-button
              type="primary"
              link
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:message:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改消息对话框 -->
    <el-dialog :title="title" v-model="open" width="960px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="消息类型" prop="messageType">
              <el-select v-model="form.messageType" placeholder="请选择消息类型" :disabled="optType === 'view'">
                <el-option
                    v-for="dict in sys_message_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="消息级别" prop="messageLevel">
              <el-select v-model="form.messageLevel" placeholder="请选择消息级别" :disabled="optType === 'view'">
                <el-option
                    v-for="dict in sys_message_level"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收人" prop="recipientNick">
              <el-input v-model="form.recipientNick" readonly="readonly" placeholder="请选择接收人" :disabled="optType === 'view'">
                <template #append>
                  <el-button @click="handleUserSelect" icon="Search" :disabled="optType === 'view'"></el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标题" prop="messageTitle">
              <el-input v-model="form.messageTitle" placeholder="请输入标题" :disabled="optType === 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="内容">
              <template v-if="optType === 'view'">
                <editor v-model="form.messageContent" :min-height="192" :read-only="true"/>
              </template>
              <template v-else>
                <editor v-model="form.messageContent" :min-height="192" />
              </template>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="optType !== 'view'">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div class="dialog-footer" v-else>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 人员选择组件 -->
    <UserSingleSelect v-model="userSelectVisible" @onSelected="onUserSelected"></UserSingleSelect>
  </div>
</template>

<script setup name="Message">
import {ref, reactive, getCurrentInstance, onMounted} from 'vue'
import {listMessage, getMessage, delMessage, addMessage, updateMessage, getMyMessage} from "@/api/system/message";
import UserSingleSelect from "@/components/userSelect/single.vue"

// 获取组件实例
const {proxy} = getCurrentInstance()

// 定义字典
const {
  sys_message_type,
  sys_message_status,
  sys_message_level
} = proxy.useDict("sys_message_type", "sys_message_status", "sys_message_level")

// 定义变量
const messageList = ref([])
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const open = ref(false)
const userSelectVisible = ref(false) // 用于控制用户选择组件的显示
const optType = ref("") // 操作类型：add-新增，edit-编辑，view-查看

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  messageType: null,
  messageLevel: null,
  messageTitle: null,
  messageContent: null,
  senderId: null,
  senderName: null,
  senderNick: null,
  recipientId: null,
  recipientName: null,
  recipientNick: null,
  processTime: null,
  callBack: null,
  status: null,
  deletedFlag: null
})

// 表单参数
const form = reactive({
  messageId: null,
  messageType: null,
  messageLevel: null,
  messageTitle: null,
  messageContent: null,
  senderId: null,
  senderName: null,
  senderNick: null,
  recipientId: null,
  recipientName: null,
  recipientNick: null,
  processTime: null,
  callBack: null,
  status: "0",
  deletedFlag: null,
  remark: null,
  attr1: null,
  attr2: null,
  attr3: null,
  attr4: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null
})

// 表单校验规则
const rules = reactive({
  /*messageType: [
    {required: true, message: "消息类型不能为空", trigger: "change"}
  ],
  messageLevel: [
    {required: true, message: "消息级别不能为空", trigger: "blur"}
  ],
  messageTitle: [
    {required: true, message: "消息标题不能为空", trigger: "blur"}
  ],
  messageContent: [
    {required: true, message: "消息内容不能为空", trigger: "blur"}
  ],
  recipientName: [
    {required: true, message: "接收人不能为空", trigger: "blur"}
  ]*/
})

// 查询消息列表
function getList() {
  loading.value = true;
  getMyMessage(queryParams).then(response => {
    messageList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 组件挂载时查询数据
onMounted(() => {
  getList();
})

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  Object.assign(form, {
    messageId: null,
    messageType: null,
    messageLevel: null,
    messageTitle: null,
    messageContent: null,
    senderId: null,
    senderName: null,
    senderNick: null,
    recipientId: null,
    recipientName: null,
    recipientNick: null,
    processTime: null,
    callBack: null,
    status: "0",
    deletedFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  });
  proxy.resetForm("formRef");
}

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

// 重置按钮操作
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.messageId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
function handleAdd() {
  reset();
  optType.value = "add";
  open.value = true;
  title.value = "添加消息";
}

// 修改按钮操作
function handleUpdate(row) {
  reset();
  const messageId = row.messageId || ids.value
  getMessage(messageId).then(response => {
    Object.assign(form, response.data);
    optType.value = "edit";
    open.value = true;
    title.value = "修改消息";
  });
}

// 查看按钮操作
function handleView(row) {
  reset();
  const messageId = row.messageId;
  getMessage(messageId).then(response => {
    Object.assign(form, response.data);
    optType.value = "view";
    open.value = true;
    title.value = "查看消息";
    
    // 如果状态是未读，则更新为已读
    if (response.data.status === "UNREAD") {
      // 克隆表单数据并更新状态
      const updateData = {...response.data, status: "READ"};
      updateMessage(updateData).then(() => {
        // 更新列表中的状态
        getList();
      });
    }
  });
}

// 提交按钮
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      if (form.messageId != null) {
        updateMessage(form).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMessage(form).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作
function handleDelete(row) {
  const messageIds = row.messageId || ids.value;
  proxy.$modal.confirm('是否确认删除消息编号为"' + messageIds + '"的数据项？').then(function () {
    return delMessage(messageIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

// 导出按钮操作
function handleExport() {
  proxy.download('system/message/export', {
    ...queryParams
  }, `message_${new Date().getTime()}.xlsx`)
}

function handleUserSelect() {
  userSelectVisible.value = true;
}

function onUserSelected(row) {
  if (row != null) {
    form.recipientId = row.userId;
    form.recipientName = row.userName;
    form.recipientNick = row.nickName;
  }
  // 关闭用户选择对话框
  userSelectVisible.value = false;
}
</script>
