<template>
  <div style="padding-top: 13vw">
    <TopNav navTitle="打卡" :showRight="true" :showLeft="true" @clickRight="onClickRight" />
    <div class="main_box">
      <!-- <div class="top_box">
        <div class="left_top">
          <div class="top_text">上班：09:00:00</div>
          <div class="tip_text">未打卡</div>
        </div>
        <div class="left_top">
          <div class="top_text">下班：09:00:00</div>
          <div class="tip_text">未打卡</div>
        </div>
      </div> -->
      <div class="upload_box">
        <div class="image_box" v-if="baseUrl">
          <van-icon name="close" class="close_icon" @click="clearImage" color="#000" size="24px" />
          <van-image :src="baseUrl" @click="onClickImg(baseUrl)" style="flex: 1">
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
          </van-image>
        </div>
        <div class="upload_icon_box" v-else>
          <van-icon @click="photoFn" name="plus" />
        </div>
        <!-- <van-uploader v-model="clockList" :max-count="1" :after-read="afterRead" capture="camera"
          :before-read="beforeRead" accept="image/*" /> -->
        <div class="upload_tip"><span style="color: red;">*</span>须拍摄实景图才可进行打卡</div>
      </div>
      <div class="dk_box">
        <div class="circle_box" @click="workFn">
          {{ workTips ? workTips : '打卡' }}
        </div>
        <!-- <div class="dk_tip" v-show="rangeShow"><van-icon name="checked" color="#08B353" />已进入考勤范围：德阳市某某某</div>
        <div class="dk_tip" v-show="!rangeShow"><van-icon name="clear" color="red" />未进入考勤范围：德阳市某某某</div> -->
      </div>
      <!-- <div class="bzt_box">
        <div style="color: #75787F;">时间轴</div>
        <van-steps direction="vertical" :active="-1" active-color="#1DB1FF">
          <van-step>
            <div style="color:#000">上班打卡</div>
            <img src="@/assets/images/menu-dk.png" alt="">
          </van-step>
          <van-step style="color:#000">
            <div>下班打卡</div>
            <img src="@/assets/images/menu-dk.png" alt="">
          </van-step>
        </van-steps>
      </div> -->
      <div class="choose_dw">
        <van-button type="primary" block @click="chooseDwFn">{{ workTips ? workTips : '点位选择' }}</van-button>
        <van-popup v-model:show="showPicker" position="bottom">
          <van-picker :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
        </van-popup>
      </div>
    </div>
  </div>
</template>
<script setup>
import TopNav from "../../../components/topNav.vue";
import { qcckGet, qcckPost } from "../../../api/qcckApi.js";
import ImageCompressor from "image-compressor.js";
import {
  timeValidate
} from "../../../utils/tools.js";
import { ImagePreview } from "vant";
import { getMybbTodayNew } from "../../../api/common";
import { onMounted, ref } from 'vue';
import { upImage } from "@/api/common";
import { hintToast } from "@/utils/tools";
import router from "@/router";
const clockList = ref();
const rangeShow = ref(true);
const showPicker = ref(false);
const columns = ref([
]);
const params = ref({
  bbid: "",//报备id,
  bxdid: "",//必巡id
  tpid: '',//附件
})
const baseUrl = ref("");
const workTips = ref()
const Loadtion = ref({
  jd: "暂无",
  wd: "暂无",
  radius: 5000
});
// 文件预览
async function afterRead(file) {
  file.message = "上传中...";
  let fileBlob = await _compressImage(file.file);
  let fileData = new File([fileBlob], fileBlob.name, { type: fileBlob.type });
  const data = new FormData();
  data.append("file", fileData);
  file.status = "uploading";
  upImage(data).then((res) => {
    console.log(res, 'res');
    file.status = "done";
    file.message = "上传成功";
    params.value.tpid = res;
  });
}



const beforeRead = (file) => {
  // 判断相册里面的照片是不是最新拍摄的照片
  let timestamp = file.lastModified;
  let newTime = new Date().getTime() - 5 * 60 * 1000;
  if (timestamp < newTime) {
    hintToast('请重新拍摄最新时间的拍照')
    return true
  } else {
    return true
  }
}
const photoFn = () => {
  try {
    bridge.pZ("photo");
  } catch (err) {
    console.log(err, 'err');

  }
}


//预览图片
function onClickImg(url) {
  ImagePreview([url]);
}
// 删除图片
const clearImage = () => {
  baseUrl.value = ""
}
//压缩图片
const _compressImage = (file) => {
  return new Promise((resolve, reject) => {
    new ImageCompressor(file, {
      quality: 0.6, //压缩质量
      success(res) {
        resolve(res);
      },
      error(e) {
        reject(e);
      },
    });
  });
};
//获取当前位置信息
function _getUserLocation(sfdw) {
  let { lng, lat, zbly } = getLocation();
  if (lng && lat) {
    Loadtion.value.jd = lng;
    Loadtion.value.wd = lat;
    getBxList()
  } else {
    hintToast("暂无坐标信息");
  }
}
const chooseDwFn = () => {
  showPicker.value = true;
}
const onConfirm = (e) => {
  workTips.value = e.text;
  params.value.bxdid = e.value;
  showPicker.value = false;
}
// 上班打卡
const workFn = () => {
  if (params.value.tpid == '') {
    hintToast('请拍照再打卡');
    return
  }
  qcckPost(params.value, "/mosty-qwzx/tbQwXfbb/addXfbbDk").then(res => {
    hintToast('打卡成功');
    router.back()
  })
}
const onClickRight = () => {
  router.push('/clockList')
}
// 获取报备id
const getBbInfo = () => {
  getMybbTodayNew().then(res => {
    params.value.bbid = res ? res.id : '';
  })
}
// 获取必训点
const getBxList = () => {
  qcckGet(Loadtion.value, "/mosty-jcgl/tbJcglBxd/selectNearbyList").then(res => {
    console.log(res, 'res');
    columns.value = res.map((item) => {
      return { text: item.bxdMc, value: item.id }
    })

  })
}
function setimage_base64(pzid, base64) {
  console.log(base64, 'base64');
  baseUrl.value = `data:image/jpeg;base64,${base64}`;
  qcckPost({base64:base64}, "/mosty-base/minio/image/upload/base64").then(res => {
    params.value.tpid = res;
  })
}
function btof(data, fileName) {
  const dataArr = data.split(',')
  const byteString = atob(dataArr[1])
  const options = {
    type: 'image/jpeg',
    endings: 'native'
  }
  const u8Arr = new Uint8Array(byteString.length)
  for (let i = 0; i < byteString.length; i++) {
    u8Arr[i] = byteString.charCodeAt(i)
  }
  return new File([u8Arr], fileName + '.jpg', options)
}
onMounted(() => {
  getBbInfo();
  _getUserLocation(true); //获取当前位置
  setInterval(() => {
    // _getUserLocation(false); //获取当前位置
  }, 5000);
  window.setimagebase64 = setimage_base64;
})
</script>
<style lang="scss" scoped>
.main_box {
  padding: 10px;
  box-sizing: border-box;
}

.top_box {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;

  .left_top {
    width: 48%;
    height: 80px;
    padding: 10px;
    box-sizing: border-box;
    top: 61px;
    left: 10px;
    gap: 0px;
    border-radius: 10px;
    opacity: 0px;
    background-color: #EDEDED;

    .tip_text {
      color: #75787F;
      margin-top: 6px;
    }
  }
}

.upload_box {
  display: flex;

  .upload_tip {
    color: #75787F;
    font-size: 13px;
  }

  .image_box {
    position: relative;
    width: 160px;
    height: 100px;

    .close_icon {
      position: absolute;
      right: 0;
      top: 0;
      z-index: 20;
    }

    ::v-deep .van-image {
      width: 100%;
    }
  }

  .upload_icon_box {
    border: 1px solid #ccc;
    text-align: center;
    width: 160px;
    height: 100px;
    line-height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
  }
}

.dk_box {
  text-align: center;

  .dk_tip {
    color: #707070;
    margin-top: 6px;
  }
}

.circle_box {
  width: 160px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  margin-top: 40%;
  border-radius: 50%;
  color: #fff;
  font-size: 20px;
  text-align: center;
  background: linear-gradient(to bottom, #1DB1FF, #007DE9);
}

.choose_dw {
  position: absolute;
  bottom: 0;
  width: 100%;
  left: 0;
}
</style>