<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="showFaceDialogNew(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>
  <el-dialog
      v-model="showFace"
      width="570px"
      center
      :show-close="false"
      style="border-radius: 20px"
      @close="Closedialog"
      :close-on-click-modal="false"
  >
    <template #header>
      <span
          class="dialog_title"
          style="
          width: 100%;
          display: block;
          text-align: left;
          font-size: 20px;
          font-weight: bold;
        "
      >录入人脸</span
      >
    </template>
    <div class="box">
      <video
          id="video"
          autoplay
          muted
          style="width: 450px; height: 450px; object-fit: cover"
      ></video
      ><br />
      <canvas
          id="canvas"
          width="450"
          height="450"
          style="position: absolute; top: 80px"
      ></canvas>
      <canvas
          id="canvasface"
          width="450"
          height="450"
          style="display: none; position: absolute; top: 0"
      ></canvas>
    </div>
    <div class="tip" v-if="!subChange" style="text-align: center">
      请保持正脸在取景框内...
    </div>
    <div class="tip" v-if="subChange">当前人脸已与其他账号绑定, 是否确认更换？</div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="fnClose"> 取消 </el-button>
        <el-button type="primary" @click="confirmFn" v-if="subChange"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, nextTick } 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";

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);
  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.map((item, index) => ({
    ...item,
    set: ["编辑", "录入人脸", "删除"],
    // set: ["编辑", "删除"],

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

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

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

//展示人脸弹窗
const showFace = ref(false);

const video = ref();
const canvas = ref();
const canvasCtx = ref();
const canvasface = ref();
const canvasfaceCtx = ref();
const timeout = ref();
const timerInter = ref();
const timerInterout = ref();
const status = ref(true);
const stopeVideo = ref();
let subChange = ref(false);
let confirm = ref(false);
const showFaceDialogNew = (row) => {
  console.log("人脸id1", row);
  let id = row.user_id;
  showFace.value = true;
  status.value = true;
  nextTick(() => {
    video.value = document.getElementById("video");
    canvas.value = document.getElementById("canvas");
    canvasCtx.value = canvas.value.getContext("2d");
    canvasface.value = document.getElementById("canvasface");
    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", playPhone(id));
  });
};

// 关闭人脸识别弹窗销毁定时器
const Closedialog = () => {
  fnClose();
};

const fnClose = () => {
  // alert(222)
  status.value = false;
  showFace.value = false;
  canvasCtx.value?.clearRect(0, 0, canvas.value.width, canvas.value.height);
  // canvasCtx.value
  video.value?.pause();
  video.value.removeEventListener("play", playPhone);
  // clearTimeout(timeout.value);
  clearInterval(timerInterout.value);
  clearInterval(timerInter.value);
  stopeVideo.value?.stop();
};
const playPhone = (id) => {
  setTimeout(() => {
    timerInterout.value = setInterval(() => {
      if (status.value) {
        setTimeout(() => {
          if (import.meta.env.VITE_FACE_TYPE == 1) {
            getPhotoLocal(id);
          } else {
            getPhotonew(id);
          }
        }, 300);
        status.value = false;
      }
    });
  }, 1000);
};
function saveAsPNG(c) {
  return c.toDataURL("image/jpeg", 0.8);
}

const getPhotonew = (id) => {
  canvasfaceCtx.value?.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value?.drawImage(video.value, 0, 0, 450, 450);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split("base64,")[1];
  // let id = JSON.parse(sessionStorage.getItem("user")).userInfo.id

  let data = { raw: newImg };
  let ip="http://"+window.location.hostname+':8081'// api的base_url

  axios({
    method: "put",
    // url: ip+ `/api/rms/web/sessions/face/${id}`,

    url: import.meta.env.VITE_FACE_SEVER_URL + `/api/rms/web/sessions/face/${id}`,
    data,
    headers: {
      "Content-Type": "application/json",
      "X-TOKEN": userId,
    },
  })
      .then((res) => {
        console.log(res, res.data.code == 200);
        if (res.data.code == 200) {
          console.log("");

          notify("录入成功", "success");
          fnClose();
        } else if (res.data.code == 409) {
          subChange.value = true;
          patchFace.value = { source_id: res.data.data.source_id, target_id: id };
        } else {
          status.value = true;
          notify(res.data.desc);
        }
      })
      .catch((err) => {
        status.value = true;
      });
};

const getPhotoLocal = (id) => {
  console.log("人脸id2", id);

  canvasfaceCtx.value?.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value?.drawImage(video.value, 0, 0, 450, 450);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split("base64,")[1];

  userRegisFace({ raw: newImg }, id)
      .then((res) => {
        if (res.code == 200) {
          newImg = [];
          message("录入成功");
          fnClose();
        } else if (res.code == 409) {
          newImg = [];
          subChange.value = true;
          patchFace.value = { source_id: res.data.source_id, target_id: id };
        } else {
          newImg = [];
          status.value = true;
        }
      })
      .catch((err) => {
        status.value = true;
      });
};
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;
}
</style>
