<template>

  <headerBar
      v-if="!isSetting"
      title="拍摄物体镜头矫正"
      :menu="menu"
      showUser
  />
  <div class="check-wrap">

    <div class="check-page flex-col" :class="isSetting ? 'check-page_seeting' : '' ">
      <div class="main-container flex-col">
        <div class="content-wrapper flex-row justify-between">
          <div class="left-panel flex-col justify-between">
            <div class="tips-container flex-row" v-if="show">
                <spanc  v-if="isSetting" class="tips-tex">
                  请在圆盘上摆上鞋子（注意左右脚），要求鞋外侧朝向拍照机，鞋子中轴线和红外线对齐,如果光亮不够，可以打开环境光源，关闭闪光灯。
                </spanc>
                <span v-else class="tips-tex">
                  请在圆盘上摆上鞋子（注意左右脚），要求鞋外侧朝向拍照机，鞋子中轴线和红外线对齐，如果光亮不够，可以打开环境光源，关闭闪光灯。
                </span>
            </div>
            <div class="camera-preview  flex col center ">
              <div class="camera-preview-img" v-if="step === 1">
                <img v-if="previewKey" class="camera-img" :src="previewSrc" />
                <div class="example-image flex-col" v-if="!isSetting && previewKey > 1"><img src="https://huilimaimg.cnhqt.com/frontend/zhihuiyin/demo.jpg?x-oss-process=image/resize,w_400"></div>
              </div>
              <template v-if="step === 2" >
                <img class="camera-img"  :src="getFilePath(imageTplPath)" />
                <span  class="camera-description">这是一张用于检查镜头是否合适的测试图</span>
              </template>

            </div>
          </div>
        </div>

        <template v-if="!isSetting">
          <div v-if="step === 1" class="action-button flex cente">
            <div @click="takePictures" class="check-button  button--primary1 flex-col"><span class="button-text" v-loading="loading">拍照检查</span>
            </div>
          </div>

          <div v-else class="action-button flex center">
            <div @click="checkConfirm(false)" class="check-button  button--white flex-col">
              <span class="button-text cu-p">重新拍照检查</span>
            </div>
            <router-link class="mar-left-20 " :to="{
              name: 'PhotographyShot'
            }">
              <div class="check-button   button--primary1 flex-col">
                <span class="button-text cu-p">确认无误，下一步</span>
              </div>
            </router-link>

          </div>

        </template>
      </div>
    </div>

    <editRow
      v-if="showrEditRow ||  isSetting"
      :id="id"
      @confirm="confirm"
      ref="editData"
      @onClose="onClose"
      @onRunMcuSingle="onRunMcuSingle"
      :addRowData="addRowData"
    />

  </div>
  <hardware-check v-if="!isSetting"
   isInitCheck
   @confirm="checkConfirm(true)"
  />
</template>
<script setup lang="ts">
import {watchEffect, ref, reactive, defineEmits, defineProps, computed, onBeforeUnmount, onMounted} from 'vue'
import client from "@/stores/modules/client";
import socket from "@/stores/modules/socket";
import icpList from '@/utils/ipc'
import useUserInfo from "@/stores/modules/user";
import headerBar from '@/components/header-bar/index.vue'
import  editRow  from './components/editRow'
const clientStore = client();
const socketStore = socket(); // WebSocket状态管理实例

const emit = defineEmits([ 'confirm','onClose']);


import  configInfo  from '@/stores/modules/config';
const configInfoStore = configInfo();

const confirm = ()=>{
  hideVideo()
  emit('confirm')
}
const onClose = ()=>{
  hideVideo()
  emit('onClose')
}
// 定义 props
const props = defineProps({
  id:{
    type: Number||String,
    default: 0
  },
  addRowData:{
    type: Object,
    default: () => {
      return { }
    }
  }
})
const menu = reactive([])
const show = ref(true)

const isSetting = computed(()=>{
  return props.id || props.addRowData.mode_type
})

const useUserInfoStore = useUserInfo()
import HardwareCheck from '@/components/check/index.vue'
import { digiCamControlWEB } from  '@/utils/appconfig'
import { getFilePath } from '@/utils/appfun'
import {ElMessage} from "element-plus";
const previewKey = ref(0)

const preview = ref(digiCamControlWEB+'liveview.jpg')



const previewSrc = computed(()=>{
  let time = new Date().getTime()
  return preview.value+'?key='+previewKey.value+'&time='+time
})
const step = ref(1)
async function checkConfirm(init){
  step.value =1
  if(menu.length === 0){
    menu.push({
      type:'developer'
    })
    menu.push({
      type:'toggleModel'
    })
  }
  if(!init) previewKey.value++;

  showVideo()
  showrEditRow.value = true
}

const init = ref(true)
function onRunMcuSingle (){
  if(init.value) {
    loading.value = false
    init.value = false
  }
}
const showrEditRow = ref(false)




let interval:any = null
function showVideo(){

    clientStore.ipc.removeAllListeners(icpList.camera.PreviewShow);

    clientStore.ipc.send(icpList.camera.PreviewShow);
    clientStore.ipc.on(icpList.camera.PreviewShow, async (event, result) => {

      setTimeout(()=>{
        interval = setInterval(()=>{
          previewKey.value++;
        },200)
      },500)

    })

}

function hideVideo(){

    clientStore.ipc.removeAllListeners(icpList.camera.PreviewHide);
    clientStore.ipc.send(icpList.camera.PreviewHide);
    clientStore.ipc.on(icpList.camera.PreviewHide, async (event, result) => {
      if(interval) clearInterval(interval)
    })

}

function goArts(){

}
const loading = ref(true)
const editData = ref(null);
const imageTplPath = ref(null)
function takePictures() {
  console.log(editData);
  console.log(editData.value.editRowData);

  if (clientStore.isClient) {

    loading.value = true;
    hideVideo()
    socketStore.sendMessage({
      type: 'run_mcu_single',
      data: {
        camera_height: Number(editData.value.editRowData.camera_height),
        camera_angle:  Number(editData.value.editRowData.camera_angle),
        led_switch:editData.value.editRowData.led_switch,
        id:0,
        mode_type:editData.value.editRowData.mode_type,
        turntable_position:Number(editData.value.editRowData.turntable_position),
        action_name:editData.value.editRowData.action_name || '测试',
        turntable_angle: Number(editData.value.editRowData.turntable_angle),
        shoe_upturn: Number(editData.value.editRowData.shoe_upturn),
        action_index:1,
        number_focus:0,
        take_picture:true,
        pre_delay:0,
        after_delay:0,
      }
    });



  }
}

// 获取主图
function  createMainImage (file_path){

  loading.value = true;
  clientStore.ipc.removeAllListeners(icpList.takePhoto.createMainImage);
  clientStore.ipc.send(icpList.takePhoto.createMainImage,{
    file_path:file_path
  });
  clientStore.ipc.on(icpList.takePhoto.createMainImage, async (event, result) => {
    if(result.code === 0 && result.data?.main_out_path){
      imageTplPath.value  = result.data?.main_out_path
      hideVideo()
      step.value = 2
      loading.value = false;
    }else if(result.msg){
      loading.value = false;
      showVideo()
      if(result.code !== 0) ElMessage.error(result.msg)
    }
    clientStore.ipc.removeAllListeners(icpList.takePhoto.createMainImage);


  });
}


//拍照成功  SmartShooter
clientStore.ipc.on(icpList.socket.message+'_smart_shooter_photo_take', async (event, result) => {
  console.log('_smart_shooter_photo_take');
  console.log(result);
  if(result.code === 0 && result.data?.photo_file_name){
    createMainImage(result.data?.photo_file_name)
  }

})


//运行的时候  直接拍照  digiCamControl
clientStore.ipc.on(icpList.socket.message+'_run_mcu_single', async (event, result) => {
  console.log('_run_mcu_single_check_on')
  console.log(result)

  if(result.code === 0 && result.data?.file_path){

    createMainImage(result.data?.file_path)

  }else if(result.msg){
    if( result.msg.indexOf('处理失败,请重试') >= 0){
      ElMessage.error(result.msg)
      step.value = 1
      loading.value = false;
      showVideo()
    }
  }

})
onMounted(async ()=>{
  if(isSetting.value)   showVideo()
  await  configInfoStore.getAppConfig()
  if(configInfoStore.appConfig.controlType === "SmartShooter"){
    preview.value = configInfoStore.appConfig.userDataPath  + "\\preview\\liveview.png"
  }
})

/**
 * 页面卸载时移除所有事件监听器。
 */
onBeforeUnmount(() => {
  hideVideo()
  clientStore.ipc.removeAllListeners(icpList.camera.takePictures);
  clientStore.ipc.removeAllListeners(icpList.camera.PreviewHide);
  clientStore.ipc.removeAllListeners(icpList.camera.PreviewShow);
  clientStore.ipc.removeAllListeners(icpList.socket.message+'_run_mcu_single');
  clientStore.ipc.removeAllListeners(icpList.socket.message+'_smart_shooter_photo_take');


})
</script>
<style scoped lang="scss">
.check-wrap {
  background-color: rgba(234, 236, 237, 1);
  display: flex;
  justify-content: left;
}
.check-page {
  width: calc(100% - 330px) ;
  position: relative;
  min-height: calc(100vh - 35px);
  overflow: hidden;
  background: #fff;

  .main-container {
    width: 100%;
    min-height: calc(100vh - 35px);
    margin-bottom: 1px;

    .content-wrapper {
      width:100%;
      padding: 10px;

      .left-panel {
        width: 100%;
        height: calc(100% - 80px);

        .tips-container {
          background-color: rgba(255, 241, 222, 0.8);
          border-radius: 4px;
          width: 100%;
          height: 40px;
          border: 1px solid rgba(255, 228, 190, 1);
          justify-content: flex-center;

          .tips-icon {
            width: 16px;
            height: 16px;
            margin: 12px 0 0 16px;
          }

          .tips-tex {
            width: 549px;
            height: 22px;
            overflow-wrap: break-word;
            color: rgba(0, 0, 0, 0.85);
            font-size: 14px;
            font-weight: NaN;
            text-align: left;
            white-space: nowrap;
            line-height: 22px;
            margin: 9px 0 0 7px;
          }

          .close-icon {
            width: 12px;
            height: 12px;
            margin: 14px 16px 0 17px;
          }
        }

        .camera-preview {
          background-color: rgba(255, 255, 255, 1);
          height:  calc(100vh - 200px);
          position: relative;
          margin-top: 20px;
          position: relative;
          .camera-description {
            position: absolute;
            bottom: 20px;
            width: 60%;
            padding: 8px 20px;
            background: rgba($color: #ffffff, $alpha: .2);
            border-radius: 20px;
            font-size: 14px;
          }
          .camera-preview-img {
            display: inline-block;
            height: 100%;
            min-width: 300px;
            position: relative;
          }

          .camera-img {
          //  width: 100%;
            display: block;
            position: relative;
            box-shadow: 0px 2px 10px 0px rgba(0, 32, 78, 0.1);
            height: 100%;
            object-fit:contain;

          }
          .example-image {
            position: absolute;
            right: 10px;
            bottom: 10px;
            background-color: rgba(216, 216, 216, 1);
            height: 135px;
            margin-top: 10px;
            width: 200px;
            img {
              width: 200px;
              height: 135px;
              display: block;
            }
          }
        }
      }

    }

    .action-button {
      width: 100%;
      text-align: center;
      margin-top: 28px;

      .check-button {
        .button-text {
          width: 180px;
          overflow-wrap: break-word;
          font-size: 16px;
          text-align: center;
          white-space: nowrap;
          height: 40px;
          line-height: 40px;
        }
      }
    }
  }
}
.check-page_seeting {
  min-height: calc(100vh - 92px);
  .main-container {
    min-height: calc(100vh - 92px);
  }
}
</style>
