<template>
  <div class="account-part">
    <div class="container">
      <div class="title">用户管理</div>
      <div class="search-container">
        <vxe-input
            class="search-input"
            v-model="search_val"
            prefix-icon="vxe-icon-search"
            placeholder="搜索"
            @blur="search"
        ></vxe-input>
      </div>
      <div class="table-box">
        <div class="table">
          <div class="table-head">
            <div class="item" v-for="(item, i) in columns" :key="i">
              {{ item.title }}
            </div>
          </div>
          <div class="table-body" v-if="dataSource.length > 0">
            <div
                v-for="(item, i) in dataSource"
                :key="i"
                :class="['item', i % 2 != 0 ? 'acv' : '']"
            >
              <div class="ims">{{ item.id }}</div>
              <div class="ims">{{ item.user_name }}</div>
              <div class="ims">{{ item.real_name }}</div>
              <div class="ims">{{ item.user_sex == 1 ? "男" : "女" }}</div>
              <div class="ims">
                {{
                  item.role_id == "35efee88-f4bc-11ee-9341-8cc84ba8982e"
                      ? "管理员"
                      : "普通用户"
                }}
              </div>
              <div class="ims">
                <span style="color: #208be9; padding-right: 20px" @click="editUser(item)">
                  {{ item?.set[0] }}
                </span>
                <span
                    style="color: #208be9; padding-right: 20px"
                    @click="bindFace(item)"
                >{{ item.set[1] }}</span
                >

                <span
                    style="color: #208be9; padding-right: 20px"
                    @click="delUserCor(item)"
                >{{ item.set[2] }}</span
                >
              </div>
            </div>
          </div>
          <div v-else class="no-box">
            <van-empty description="没有数据" />
          </div>
        </div>
      </div>
      <div class="footer">
        <div class="exit" @click="goBack">返回</div>
        <CommonPage
            :maxNum="maxPage"
            @changePage="handleCurpageChange"
            :page_no="pageInfo.page_no"
        />
        <div class="add-user" @click="addNewUser">
          <van-icon name="friends-o" />
          添加用户
        </div>
      </div>
    </div>
  </div>
  <!-- 人脸录入弹窗 -->
  <div v-if="isFace" class="mask">
    <div class="dialog_container">
      <div class="face-box">
        <video
          id="facevideo"
          autoplay
          muted
          style="
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
            transform: rotateY(180deg);
          "></video>
        <br />
        <canvas
          id="facecanvas"
          width="400"
          height="400"
          style="position: absolute; top: 18%; left: 35%"></canvas>
        <canvas
          id="facecanvasF"
          width="600"
          height="600"
          style="display: none; position: absolute; top: 0"></canvas>
      </div>
      <p>人脸绑定</p>
      <p>请保持您的正脸在取景框内...</p>
      <div @click="fnClose">返回</div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick,onBeforeUnmount  } from "vue";
import { useRouter } from "vue-router";
import { notify, message } from "@/utils/message.js";
import { getUserList, deleteUserApi } from "@/api/user.js";
import { showConfirmDialog } from "vant";
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElSwitch,
  ElRadio,
  ElRow,
  ElCol,
} from "element-plus";
import axios from "axios";
import { queryUserList,bindFaceApi} from '@/api/login'

let useInfo = JSON.parse(sessionStorage.getItem("userInfo"));
let { userId } = useInfo || {};
import { ElMessage } from "element-plus";
import CommonPage from "@/components/CommonPage.vue";
const router = useRouter();

let dataSource = ref([]);
const pageInfo = ref({
  page_no: 1,
  page_size: 5,
  search_word: "",
});
const columns = [
  {
    title: "序号",
  },
  {
    title: "用户名",
  },
  {
    title: "姓名",
  },
  {
    title: "性别",
  },
  {
    title: "角色",
  },
  {
    title: "操作",
  },
];

onMounted(() => {
  rolseList();
});

const search_val = ref("");
const search = () => {
  pageInfo.value.search_word = search_val.value;
  rolseList();
};
const maxPage = ref(1);

const rolseList = async () => {
  const res = await getUserList(pageInfo.value);
  //const res = await queryUserList(pageInfo.value);
  let { code, data, desc, pagination } = res.data;
  let total_count = pagination.total_count;
  maxPage.value = Math.ceil(total_count / pageInfo.value.page_size) || 1;

  if (code != 200) {
    notify(desc);
    return;
  }
  dataSource.value = data.users.map((item, index) => ({
    ...item,
    set: ["编辑", "录入人脸", "删除"],
    // set: ["编辑", "删除"],

    id: index + 1,
  }));
};

const addNewUser = () => {
  router.push({ path: "/addUser", query: { type: "addNewUser" } });
};

const goBack = () => {
  router.push("/home");
};

//展示人脸弹窗
const video = ref();
const canvas = ref();
const canvasCtx = ref();
const canvasface = ref();
const canvasfaceCtx = ref();
const status = ref();
const stopeVideo = ref();
const timerInter = ref();
const timeout = ref();
let isFace = ref(false);
let face_user_id = ref('');
// 人脸识别登录
const bindFace = (item) => {
  console.log(item,';;;;;;;;;;');
  face_user_id.value = item.user_id;
  status.value = true;
  isFace.value = true;
  nextTick(() => {
    video.value = document.getElementById('facevideo');
    canvas.value = document.getElementById('facecanvas');
    canvasCtx.value = canvas.value.getContext('2d');
    canvasface.value = document.getElementById('facecanvasF');
    canvasfaceCtx.value = canvasface.value.getContext('2d');

    navigator.mediaDevices?.getUserMedia({ video: true, audio: false }).then((stream) => {
      video.value.srcObject = stream;
      stopeVideo.value = stream.getTracks()[0];
      video.value.addEventListener('play', () => {
        timerInter.value = setInterval(async () => {
          if (status.value) {
            timeout.value = setTimeout(() => {
              getPhotoLocal();
            }, 1000);
            status.value = false;
          }
        });
      });
    });
  });
};

const getPhotoLocal = async () => {
  canvasfaceCtx.value.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value.drawImage(video.value, 0, 0, 400, 400);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split('base64,')[1];
  try {
    const res = await bindFaceApi({ raw: newImg }, face_user_id.value);
    console.log(res, 'ooooooo');
    let data = res.data;
    if (data.code == 200) {
      notify('绑定成功', 'success');
      fnClose();
    } else {
      notify(data.desc, 'danger');
      status.value = true;
    }
  } catch (error) {
    status.value = true;
  }
};

const saveAsPNG = (c) => {
  return c.toDataURL('image/jpeg', 0.8);
};

const fnClose = () => {
  isFace.value = false;
  canvasCtx.value?.clearRect(0, 0, canvas.value.width, canvas.value.height);
  video.value?.pause();
  clearTimeout(timeout.value);
  clearInterval(timerInter.value);
  stopeVideo.value?.stop();
};

onBeforeUnmount(() => {
  fnClose();
});
const delUserCor = (item) => {
  showConfirmDialog({
    title: "是否删除这个用户",
  })
      .then(() => {
        delUser(item);
      })
      .catch(() => {
        notify("已取消", "primary");
      });
};
const delUser = async (item) => {
  const res = await deleteUserApi(item.user_id);
  if (res.status != 200) {
    notify(res.data.desc);
    return;
  }
  notify(res.data.desc, "success");

  rolseList();
};
const editUser = (item) => {
  router.push({
    path: "/editUser",
    query: {
      role_id: item.role_id,
      user_id: item.user_id,
      name: item.real_name,
      userName: item.user_name,
      sex: item.user_sex,
    },
  });
};
// 分页
const handleCurpageChange = (type) => {
  if (type === "pre") {
    if (pageInfo.value.page_no == 1) return;
    if (pageInfo.value.page_no > 1) {
      pageInfo.value.page_no--;
    }
  } else if (type === "next") {
    if (pageInfo.value.page_no == maxPage.value) return;
    if (pageInfo.value.page_no < maxPage.value) {
      pageInfo.value.page_no = pageInfo.value.page_no + 1;
    }
  } else {
    pageInfo.value.page_no = type;
  }
  rolseList();
};
</script>

<style lang="less" scoped>
.account-part {
  padding: 12px;
  width: 100%;
  overflow: auto;
}
.container {
  width: 100%;
  padding: 16px;
  background: #f6f6f6;
  box-shadow: 0px 3px 9px 1px rgba(0, 0, 0, 0.16);
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #cccccc;
  position: relative;
  margin-bottom: 50px;
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: #343434;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 12px;
  }
  .search-container {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .search-input {
      width: 98%;
    }
  }
  .table-box {
    background: #f6f6f6;
    .table {
      overflow-y: scroll;
      .table-head {
        position: sticky;
        left: 0;
        top: 0;
        display: flex;
        padding: 0 12px;
        justify-content: space-between;
        line-height: 40px;
        background: #e6eef6;
        .item {
          flex: 1;
          font-size: 16px;
          color: #808080;
          text-align: center;
        }
        .item:last-child {
          flex: 2.5;
        }
      }
      .table-body {
        .item {
          display: flex;
          padding: 0 20px;
          height: 40px;
          font-size: 14px;
          text-align: center;
          background: #ffffff;
          justify-content: space-between;
          align-items: center;
          .ims {
            flex: 1;
          }
          .ims:last-child {
            flex: 2.5;
          }
        }

        .acv {
          background-color: #f6f6f6;
        }
      }
      .no-box {
        height: 300px;
        width: 100%;
        //line-height: 300px;
        text-align: center;
      }
    }
  }

  .footer {
    display: flex;
    font-size: 16px;
    width: 100%;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 12px 10px;
    bottom: 0;
    left: 0;
    background: #ffffff;

    .exit {
      width: 89px;
      height: 44px;
      text-align: center;
      background: linear-gradient(180deg, #ffffff 0%, #e5e5e5 100%);
      box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.26);
      border-radius: 2px 2px 2px 2px;
      border: 1px solid #e5e5e5;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .add-user {
      width: 118px;
      height: 44px;
      text-align: center;
      color: #ffffff;
      background: linear-gradient(180deg, #e24a4a 0%, #a21313 100%);
      box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.26);
      border-radius: 2px 2px 2px 2px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}
.box {
  display: flex;
  justify-content: center;
}
.mask {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.16);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  .dialog_container {
    background: #f8f8f8;
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
    border-radius: 8px 8px 8px 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 16px;
    padding: 16px;
    justify-content: space-between;
    text-align: center;
   // width: 800px;
    .face-box {
      width: 200px;
      height: 200px;
      box-shadow: 0px 4px 8px 1px rgba(97, 101, 188, 0.29);
      border-radius: 50%;
      margin-top: 20px;
      margin-bottom: 20px;
    }
  }
}
</style>
