<script>
import axios from "axios";
import { SearchUserService } from "@/api/user.js";
import { getFriendReqService } from "@/api/user.js";
import {acceptInviteService } from "@/api/user.js";
import {GetUserInfoService} from "@/api/user.js";
import {DelFGService} from "@/api/user.js";
import router from "@/router/index.js";
import Cookies from "js-cookie";
import { getFriendListService } from "@/api/chat.js";
import {sendMessageService} from "@/api/chat.js";
import { ElMessage } from 'element-plus';
export default {
  data() {
    return {
      ip: "",
      tableData: [],
      search_id: 2002,
      UserUpdateForm:{},
      keyword: "",
      FriendsRequestIsDisplay:false,
      updateDialogVisible: false,
      FriendsGRequestList:[],
      FriendsTableIsDisplay:false,
      FriendsGList:[],
      GroupList:[],
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
        id: 2002,
        keyword: "",
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getUserList() {
      let result = {};
      try {
        //判断search_id是字符串还是数字
        if(isNaN(this.search_id)){
          //是字符串，说明是关键字
          this.keyword = this.search_id;
          this.tokenData.id = -1;
          this.tokenData.keyword = this.keyword;
        }else if(isFinite(this.search_id)){
          //是数字，说明是ID
          this.tokenData.id = this.search_id;
          this.tokenData.keyword = ""; 
        }else{
          //不是数字也不是字符串
          ElMessage.error("输入错误，请输入数字或者关键字");
          return;
        }

       
        Cookies.set("search_id", this.search_id);
        Cookies.set("keyword", this.keyword);
        result = await SearchUserService(this.tokenData);
      } catch (e) {
        console.log(e);
      }
      let data = result.data;
      this.tableData = data;
    },
    async requestFriend(index) {
      var id = this.tableData[index].ID;
      var name = this.tableData[index].Name;
      let result ={}
      try{
        result =await sendMessageService({
          token: localStorage.getItem("token"),
          from_user_id: localStorage.getItem("userId"),
          to_user_id: id,
          msg: "请求加好友",
          type: 4,
        });
        if(result.code ===0){
          ElMessage.success("请求发送成功");
        }else{
          ElMessage.error("请求发送失败,请检查是否已经发送过请求或者对方已经是好友");
        }
      }catch(e){
        console.log(e);
      }
    },
    //获取好友列表
    async displayFriends(){
      let result ={}
      try{
        result = await getFriendListService(this.tokenData);
        if(result.code ===0){
          this.FriendsGList = result.data.friends;
          this.GroupList=result.data.groups;
          this.FriendsTableIsDisplay = true;
        }else{
          ElMessage.error("获取好友列表失败");
        }
      }catch(e){
        console.log(e);
      }
    },
    //删除好友
    async DelFriendsOrGroup(index){
      var id = this.FriendsGList[index].id;
      var name = this.FriendsGList[index].name;
      let result ={}
      try{
        result =await DelFGService({
          token: localStorage.getItem("token"),
          from_user_id: localStorage.getItem("userId"),
          to_user_id: id,
          msg: "删除好友",
          type: 1,
        });
        if(result.code ===0){
          ElMessage.success("删除好友成功");
          this.displayFriends();
        }else{
          ElMessage.error("删除好友失败");
        }
      }catch(e){
        console.log(e);
      }
    },

    //接受好友请求
    async AcceptFriendsOrGroup(index){
      var id = this.FriendsGRequestList[index].id;
      var im_id = this.FriendsGRequestList[index].im_id;
      var name = this.FriendsGRequestList[index].name;
      let result ={}
      try{
        result =await acceptInviteService({
          token: localStorage.getItem("token"),
          id: im_id,
          from_user_id: localStorage.getItem("userId"),
          to_user_id: id,
          msg: "接受好友请求",
          index: 1,
          type: 4,
        });
        if(result.code ===0){
          ElMessage.success("接受好友请求成功");
          this.displayFriendReq()
        }else{
          ElMessage.error("接受好友请求失败");
        }
      }catch(e){
        console.log(e);
      }
    },
    
    //获取好友请求列表
    async displayFriendReq(){
      let result ={}
      try{
        result =await getFriendReqService(this.tokenData)
        if(result.code ===0){
          this.FriendsGRequestList = result.data;
          this.FriendsRequestIsDisplay = true;
        }else{
          ElMessage.error("获取好友请求列表失败");
        }
      }catch(e){
        console.log(e);
      }

    },
    onSubmit() {
      getUserList({ token: token });
    },
    handleSizeChange() {
      alert("每页记录数变化" + val);
    },
    handleCurrentChange() {
      alert("页码发生变化" + val);
    },
    startChat(index){

      localStorage.setItem("to_user_id", this.tableData[index].ID);
      localStorage.setItem("to_user_name", this.tableData[index].Name);
      router.push("/im");

    },

    async displayMyInfo() {
      let result = {};
      try{
        //获取用户信息
        result = await GetUserInfoService(this.tokenData)
        if(result.code ===0){
          this.UserUpdateForm.id = result.data.ID;
          this.UserUpdateForm.name = result.data.Name;
          this.UserUpdateForm.email = result.data.Email;
          this.UserUpdateForm.age = result.data.Age;
          this.UserUpdateForm.role = result.data.Role;
          this.UserUpdateForm.gender = result.data.Gender;
          this.UserUpdateForm.create_time = result.data.CreatedAt;
        }
      }catch(e){
        console.log(e);
      }
      this.updateDialogVisible= true;
    },

    handleMenuSelect(val) {
      router.push(val);
    },
    toVideoList() {
      router.push("/videoList");
    },
    // 修改条纹颜色
    tableRowClassName({ row, rowIndex }) {
      if (row.human === 1) {
        return {
          background: "#488aff",
        };
      } else {
        return "";
      }
    },
  },

  // 生命周期钩子会在组件生命周期的各个不同阶段被调用
  // 例如这个函数就会在组件挂载完成后被调用
  async mounted() {
    let now = new Date();
    if (localStorage.getItem("token") === null) {
      router.push("/login");
    }
    this.search_id = Cookies.get("search_id")?Cookies.get("search_id"):2002;
    this.keyword = Cookies.get("keyword")?Cookies.get("keyword"):"";
  },
};
</script>

<template>
  <div>
    <el-button
      type="primary"
      size="mini"
      @click.prevent="handleMenuSelect('/videoList')"
      >视频列表</el-button
    >
    <el-button
      type="primary"
      size="mini"
      @click.prevent="handleMenuSelect('/device')"
      >设备管理</el-button
    >
    <el-button
      type="primary"
      size="mini"
      @click.prevent="handleMenuSelect('/User')"
      >用户</el-button
    >
    <el-button
      type="primary"
      size="mini"
      @click.prevent="handleMenuSelect('/cid')"
      >集成部署</el-button
    >

    <el-container style="height: 700px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)"
        >用户搜索列表</el-header
      >
      <el-container>
        <el-main>
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-col :span="8">
            <!-- 搜索与添加区域 -->
            <el-input
              placeholder="请输入ID或关键字"
              v-model="search_id"
              clearable
              @clear="getUserList"
            >
            </el-input>
            <template #append>
              <el-button @click="getUserList"
                ><el-icon><search /></el-icon
              ></el-button>
            </template>
          </el-col>
          <el-form-item>
              <el-button type="primary" @click="displayFriends()"
                >好友列表</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="displayFriendReq()"
                >好友请求</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="displayMyInfo()"
                >我的信息</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-dialog
                v-model="updateDialogVisible"
                title="我的信息"
                width="50%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="updateFormRef"
                  :model="UserUpdateForm"
                  :rules="UserUpdateFormRules"
                  label-width="70px"
                >
                <el-form-item label="ID" prop="id">
                    <el-input
                      disabled
                      v-model="UserUpdateForm.id"
                      autocomplete="on"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="用户名" prop="name">
                    <el-input
                      v-model="UserUpdateForm.name"
                      autocomplete="on"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="UserUpdateForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="Age" prop="age">
                    <el-input v-model="UserUpdateForm.age"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="gender">
                    <el-input v-model="UserUpdateForm.gender"></el-input>
                  </el-form-item>
                  <el-form-item label="权限" prop="role">
                    <el-input v-model="UserUpdateForm.role" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="注册时间" prop="role">
                    <el-input v-model="UserUpdateForm.create_time"></el-input>
                  </el-form-item>
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="updateDevice()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>
            <!-- 表单 -->
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-form-item>
              <el-button
                class="el-button--danger"
                type="primary"
                @click="getUserList()"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
          </el-form>
          


          <el-dialog
            title="好友请求"
            width="50%"
            v-model="FriendsRequestIsDisplay"
            center>

            <el-table :data="FriendsGRequestList" width="100%">
              <el-table-column prop="id" label="id" width="80"></el-table-column>
              <el-table-column
                prop="name"
                label="名称"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="email"
                label="用户邮箱"
                width="180"
              ></el-table-column>
              <el-table-column
                prop="age"
                label="用户Age"
                width="120"
              ></el-table-column>
              <el-table-column>
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    @click.prevent="AcceptFriendsOrGroup(scope.$index)"
                    >同意请求</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    @click.prevent="RefuseFriendsOrGroup(scope.$index)"
                    >拒绝请求</el-button>
                  </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          
          <el-dialog
            title="用户好友"
            width="40%"
            v-model="FriendsTableIsDisplay"
            center>

            <el-table :data="FriendsGList" width="100%">
              <el-table-column prop="id" label="id" width="80"></el-table-column>
              <el-table-column
                prop="name"
                label="名称"
                width="100"
              ></el-table-column>
              <el-table-column
                prop="email"
                label="用户邮箱"
                width="180"
              ></el-table-column>
              <el-table-column>
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    @click.prevent="DelFriendsOrGroup(scope.$index)"
                    >删除好友或群组</el-button
                  >
                  </template>
              </el-table-column>
            </el-table>
          </el-dialog>
          

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table :data="tableData" width="100%" border>
            :row-style="this.tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="Name"
              label="名称"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="Email"
              label="用户邮箱"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="Age"
              label="用户Age"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="Gender"
              label="用户性别"
              width="80"
            ></el-table-column>
            <el-table-column label="操作" width="300">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="startChat(scope.$index)"
                  >聊天</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="requestFriend(scope.$index)"
                  >请求加好友</el-button
                >

                <!-- <el-button type="danger" size="mini">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <br />

          <!-- 分页条 -->
          <!-- Pagination 分页 -->
          <!-- <el-pagination
            background
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="1000"
          ></el-pagination> -->
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>