<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发送人" prop="senderName">
        <el-input
          v-model="queryParams.senderName"
          placeholder="请输入发送用户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="拼桌名称" prop="teamName">
        <el-input
          v-model="queryParams.teamName"
          placeholder="请输入拼桌名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable @change="handleQuery">
          <el-option
            v-for="dict in dict.type.message_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <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>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chatList" @selection-change="handleSelectionChange" :default-sort="defaultSort"  @sort-change="onSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <template v-for="column of showColumns">
        <el-table-column
            :key="column.key"
            :label="column.label"
            :prop="column.key"
            :align="column.align"
            :min-width="column.minWidth"
            :sort-orders="orderSorts"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.overflow"
            :width="column.width"
        >
          <template slot-scope="d">
            <template v-if="column.key === 'id'">
              {{d.row[column.key]}}
            </template>
            <template v-else-if="column.key === 'isRead'">
              <dict-tag :options="dict.type.is_read" :value="d.row[column.key]"/>
            </template>
            <template v-else-if="column.key === 'type'">
              <dict-tag :options="dict.type.message_type" :value="d.row.type"/>
            </template>
            <template v-else-if="column.key === 'content'">
              <div v-if="d.row.type === MessageType.PICTURE">
                <image-preview
                  :src="d.row.content"
                  :width="32"
                  :height="32"
                >
                </image-preview>
              </div>
              <div v-else-if="d.row.type === MessageType.VIDEO">
                <video :src="d.row.content" style="width: 50px; height: 50px; background-color: #000; cursor: pointer;" @click="handleVideo(d.row)"/>
              </div>
              <div v-else>{{ d.row.content }}</div>
            </template>
            <template v-else-if="column.key === 'senderName'">
              <i class="el-icon-user" v-if="d.row.sendId"/>
              <span v-if="d.row.sendId">
                 <user-link :id="d.row.sendId" :text="d.row.senderName"/>
              </span>
              <span v-else>
                系统消息
              </span>
            </template>
            <template v-else>
              {{d.row[column.key]}}
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="openDrawer(scope.row)"
          >接收列表</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-has-permi="['bst:chat:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-has-permi="['bst:chat:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <chat-drawer ref="chatDrawer"/>

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

    <el-dialog title="聊天视频" :visible.sync="videoVisible" width="800px">
      <video :src="row.content" style="width: 100%; height: fit-content; background-color: #000; max-height: 600px;" controls/>
    </el-dialog>


    <!-- 添加或修改聊天记录列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <form-col :span="span"  label="发送人名称" prop="senderName">
            <el-input v-model="form.senderName" placeholder="请输入发送人名称" />
          </form-col>
          <form-col :span="span"  label="接收人名称" prop="receiverName">
            <el-input v-model="form.receiverName" placeholder="请输入接收人名称" />
          </form-col>
          <form-col :span="span"  label="拼桌名称" prop="teamName">
            <el-input v-model="form.teamName" placeholder="请输入拼桌名称" />
          </form-col>
          <form-col :span="span"  label="是否已读" prop="isRead">
            <el-select v-model="form.isRead" placeholder="请选择是否已读">
              <el-option
                v-for="dict in dict.type.is_read"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </form-col>

          <form-col :span="span"  label="消息类型 1-文本 2-图片 3-视频" prop="type">
            <el-select v-model="form.type" placeholder="请选择消息类型 1-文本 2-图片 3-视频">
              <el-option
                v-for="dict in dict.type.message_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </form-col>
          <form-col :span="span"  label="读取时间" prop="readTime">
            <el-date-picker clearable
              v-model="form.readTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择读取时间">
            </el-date-picker>
          </form-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChat, getChat, delChat, addChat, updateChat } from "@/api/bst/chat";
import { $showColumns } from '@/utils/mixins';
import FormCol from "@/components/FormCol/index.vue";
import UserLink from "@/views/system/user/UserLink.vue";
import ChatDrawer from "@/views/bst/chat/chatDrawer.vue";
import {MessageType, TeamType, TeamUserStatus} from "@/utils/constants";

  // 默认排序字段
const defaultSort = {
  prop: "createTime",
  order: "descending"
}

export default {
  name: "Chat",
  computed: {
    MessageType() {
      return MessageType
    },
    TeamUserStatus() {
      return TeamUserStatus
    },
    TeamType() {
      return TeamType
    }
  },
  mixins: [$showColumns],
  dicts: ['is_read', 'message_type'],
  props: {
    query: {
      type: Object,
      default: () => ({})
    }
  },
  components: {ChatDrawer, UserLink, FormCol},
  data() {
    return {
      row: {},
      videoVisible: false,
      span: 24,
      // 字段列表
      columns: [
        {key: 'teamName', visible: true, label: '拼桌名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'senderName', visible: true, label: '发送人名称', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'type', visible: true, label: '消息类型', minWidth: null, sortable: true, overflow: false, align: 'center', width: null},
        {key: 'content', visible: true, label: '内容', minWidth: null, sortable: true, overflow: true, align: 'center', width: null},
        {key: 'createTime', visible: true, label: '创建时间', minWidth: null, sortable: false, overflow: false, align: 'center', width: "100"},
      ],
      // 排序方式
      orderSorts: ['ascending', 'descending', null],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天记录列表表格数据
      chatList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      defaultSort,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: defaultSort.prop,
        isAsc: defaultSort.order,
        sendId: null,
        receiveId: null,
        teamId: null,
        isRead: null,
        deleted: null,
        type: null,
        readTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sendId: [
          { required: true, message: "发送人ID不能为空", trigger: "blur" }
        ],
        receiveId: [
          { required: true, message: "接收人ID不能为空", trigger: "blur" }
        ],
        teamId: [
          { required: true, message: "拼桌ID不能为空", trigger: "blur" }
        ],
        isRead: [
          { required: true, message: "是否已读 0-未读 1-已读不能为空", trigger: "change" }
        ],
        deleted: [
          { required: true, message: "逻辑删除 0-否 1-是不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "消息类型 1-文本 2-图片 3-视频不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.queryParams = {
      ...this.queryParams,
      ...this.query
    }
    this.getList();
  },
  methods: {
    handleVideo(row) {
      this.row = row;
      this.videoVisible = true;
    },
    // 查看消息详情
    openDrawer(row) {
      this.$refs.chatDrawer.loadData(row.id);
    },
    /** 当排序按钮被点击时触发 **/
    onSortChange(column) {
      if (column.order == null) {
        this.queryParams.orderByColumn = defaultSort.prop;
        this.queryParams.isAsc = defaultSort.order;
      } else {
        this.queryParams.orderByColumn = column.prop;
        this.queryParams.isAsc = column.order;
      }
      this.getList();
    },
    /** 查询聊天记录列表列表 */
    getList() {
      this.loading = true;
      listChat(this.queryParams).then(response => {
        this.chatList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendId: null,
        receiveId: null,
        teamId: null,
        isRead: null,
        deleted: null,
        type: null,
        createTime: null,
        readTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加聊天记录列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getChat(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改聊天记录列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateChat(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChat(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除聊天记录列表编号为"' + ids + '"的数据项？').then(function() {
        return delChat(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bst/chat/export', {
        ...this.queryParams
      }, `chat_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
