<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">
        <vxe-table :data="dataSource" height="450px" show-overflow stripe>
          <vxe-column
            v-for="col of columns"
            :field="col.field"
            :title="col.title"
            :min-width="col.width">
            <template #default="{ row }">
              <span v-if="col.field === 'user_sex'">
                {{ row.user_sex == 1 ? '男' : '女' }}
              </span>
              <span v-else-if="col.field === 'role_id'">
                {{ row.role_id == '34efee88-f4bc-11ee-9341-8cc84ba8982e' ? '普通用户' : '管理员' }}
              </span>
              <span v-else>
                {{ row[col.field] }}
              </span>
            </template>
          </vxe-column>
          <vxe-column title="操作" :min-width="300">
            <template #default="{ row }">
              <span style="color: #208be9; padding-right: 40px" @click="editUser(row)">编辑</span>
              <span style="color: #208be9; padding-right: 40px" @click="bindFace(row)">
                录入人脸
              </span>
              <!-- <span style="color: #208be9" @click="editUser(row)">添加条码</span> -->
              <span style="color: #cf4a4a" @click="delUserCor(row)">删除</span>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="footer">
        <div class="exit" @click="goBack">返回</div>
        <!-- <CommonPage
            :maxNum="pageInfo.maxPage"
            @changePage="handleCurpageChange"
            :page_no="pageInfo.page_no" /> -->
        <div class="add-user" @click="addNewUser">
          <van-icon name="friends-o" />
          添加用户
        </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"></video>
          <br />
          <canvas
            id="facecanvas"
            width="400"
            height="400"
            style="position: absolute; top: 15%; 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>
  </div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { notify } from '@/utils/message.js';
import { getUserList, deleteUserApi } from '@/api/user.js';
import { bindFaceApi } from '@/api/login.js';
import { showConfirmDialog } from 'vant';

let faceUrl = ref('');
faceUrl.value = 'http://' + window.location.hostname + ':8081';
const router = useRouter();

let dataSource = ref([]);
const pageInfo = ref({
  page_no: 1,
  page_size: 10000,
  maxPage: 5
});
const columns = ref([
  {
    title: '用户名',
    width: 220,
    field: 'user_name'
  },
  {
    title: '姓名',
    width: 160,
    field: 'real_name'
  },
  {
    title: '性别',
    width: 120,
    field: 'user_sex'
  },
  {
    title: '角色',
    width: 160,
    field: 'role_id'
  }
]);

onMounted(() => {
  rolseList();
});
let search_val = ref('');
const rolseList = async () => {
  const res = await getUserList({
    ...pageInfo.value,
    real_name: search_val.value
  });
  let { code, desc, pagination } = res?.data || {};
  if (code !== 200) {
    notify(desc);
    return;
  }
  dataSource.value = res?.data?.data || [];
  console.log(pagination, res);
  pageInfo.value = {
    ...pagination,
    maxPage:
      Math.floor(pagination.total_count / pagination.page_size) +
      (pagination.total_count % pagination.page_size ? 1 : 0)
  };
};
const search = () => {
  if (search_val.value) {
    rolseList();
  }
};
const addNewUser = () => {
  router.push({ path: '/addUser', query: { type: 'addNewUser' } });
};

const goBack = () => {
  router.go(-1);
};

// 编辑用户
const editUser = (item) => {
  router.push({
    path: '/editUser',
    query: {
      role_id: item.role_id,
      real_name: item.real_name,
      user_id: item.user_id,
      user_name: item.user_name,
      user_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 == pageInfo.value.maxPage) return;
//     if (pageInfo.value.page_no < pageInfo.value.maxPage) {
//       pageInfo.value.page_no = pageInfo.value.page_no + 1;
//     }
//   } else {
//     pageInfo.value.page_no = type;
//   }
// };

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) => {
  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(() => {
              if (import.meta.env.VITE_FACE_TYPE == 1) {
                getPhotoLocal();
              } else {
                getPhotonew();
              }
            }, 1000);
            status.value = false;
          }
        });
      });
    });
  });
};
const getPhotonew = 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];

  let data = { raw: newImg };
  const res = await bindFaceApi(faceUrl.value, data, face_user_id.value);
  if (res.data.code == 200) {
    notify('绑定成功');
    face_user_id.value = '';
    fnClose();
  } else {
    status.value = true;
  }
};

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(faceUrl.value, { 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();
};
const delUserCor = (item) => {
  showConfirmDialog({
    title: '提示',
    message: `是否删除这个用户`,
    className: 'BaseApp-MessageBox-Confirm'
  })
    .then(() => {
      delUser(item);
    })
    .catch(() => {
      
    });
};
const delUser = async (item) => {
  const res = await deleteUserApi(item.user_id);
  let { code, desc } = res.data;
  if (code != 200) {
    notify(desc);
    return;
  }
  notify(desc, 'success ');

  rolseList();
};
onBeforeUnmount(() => {
  fnClose();
});
</script>

<style lang="less" scoped>
.account-part {
  padding: 0 40px;
  width: 100%;
  overflow: auto;
}
.container {
  width: 100%;
  height: 870px;
  padding: 52px 40px 0;
  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;
  overflow: auto;
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 48px;
    color: #343434;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 30px;
  }
  .search-container {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .search-input {
      width: 99.5%;
      height: 100px;
      font-size: 40px;
    }
  }
  .table-box {
    background: #f6f6f6;
    :deep(.vxe-table) {
      box-sizing: border-box;
      .vxe-cell {
        padding: 10px 0 10px 20px;
      }
      .vxe-table--header {
        .vxe-header--row {
          .vxe-header--column {
            height: 100px;
            text-align: center;

            &:first-child {
              .vxe-cell {
                padding-left: 90px;
              }
            }
          }
        }
      }
      .vxe-table--body {
        .vxe-body--row {
          height: 100px;
          .vxe-body--column {
            height: 100px;
            &:first-child {
              .vxe-cell {
                padding-left: 90px;
              }
            }
          }
        }
      }
    }
    // .table {
    //   overflow-y: scroll;
    //   .table-head {
    //     position: sticky;
    //     left: 0;
    //     top: 0;
    //     display: flex;
    //     padding: 32px 36px;
    //     background: #e6eef6;
    //     .item {
    //       font-size: 36px;
    //       color: #808080;
    //       text-align: left;
    //     }
    //   }
    //   .table-body {
    //     .item {
    //       display: flex;
    //       padding: 32px 36px;
    //       font-size: 36px;
    //       text-align: left;
    //       background: #ffffff;
    //       align-items: center;
    //       .ims {
    //       }
    //     }
    //     .acv {
    //       background-color: #f6f6f6;
    //     }
    //   }
    //   .no-box {
    //     height: 300px;
    //     width: 100%;
    //     //line-height: 300px;
    //     text-align: center;
    //   }
    // }
  }

  .footer {
    display: flex;
    font-size: 40px;
    width: 100%;
    justify-content: space-between;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 19px 80px 40px;
    bottom: 0;
    left: 0;

    .exit {
      width: 200px;
      height: 100px;
      background: #ffffff;
      box-shadow: 0px -3px 6px 1px rgba(0, 0, 0, 0.16);
      border-radius: 0px 0px 0px 0px;
      border: 1px solid #dcdcdc;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .add-user {
      width: 292px;
      height: 100px;
      text-align: center;
      color: #ffffff;
      background: linear-gradient(180deg, #fe7a82 0%, #82030c 100%);
      box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.2);
      border-radius: 8px 8px 8px 8px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .page-container {
      width: 200px;
      display: flex;
      justify-content: space-between;
      transform: scale(2);
    }
  }
}
.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: 24px 24px 24px 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 36px;
    padding: 48px;
    justify-content: space-between;
    text-align: center;
    width: 798px;
    .face-box {
      width: 600px;
      height: 600px;
      box-shadow: 0px 4px 8px 1px rgba(97, 101, 188, 0.29);
      border-radius: 50%;
      margin-top: 42px;
      margin-bottom: 42px;
    }
  }
}
</style>
