<template>
  <div>
    <Transition :enter-active-class="proxy?.animate.mask.enter" :leave-active-class="proxy?.animate.mask.leave">
      <div class="mask" v-if="optionWindow.show"></div>
    </Transition>
    <Transition :enter-active-class="proxy?.animate.dialog.enter" :leave-active-class="proxy?.animate.dialog.leave">
      <div class="optionWindow" v-if="optionWindow.show">
        <div class="box">
          <div class="top">
            <div class="title">{{ optionWindow.title }}</div>
            <div class="close" @click="close"></div>
          </div>
          <div class="content" v-if="optionWindow.type == 'add'">
            <div class="formList">
              <div class="left left1">项目：</div>
              <div class="right"> <el-select v-model="optionForm.project" placeholder="请选择项目">
                  <el-option v-for="item in projectList" :key="item.key" :label="item.name" :value="item.key" />
                </el-select></div>
            </div>
            <div class="formList">
              <div class="left left1">工作站：</div>
              <div class="right"> <el-select v-model="optionForm.worker" placeholder="请选择工作站">
                  <el-option v-for="(item, k) in workers" :key="item[0]" :label="k" :value="item[0]">
                    <span style="float: left; font-size: 15px">{{ k }} <i v-if="item[3] == '待重启'"
                        class="el-icon-refresh"></i> </span>
                    <span style="float: right; color: #8492a6; font-size: 15px">{{ item[1] }}</span>
                  </el-option>
                </el-select></div>
            </div>
            <div class="formList" v-if="optionForm.project">
              <div class="left left1">序号(极值:{{ eMaxId }})：</div>
              <div class="right"> <el-select v-model="optionForm.mIdx" placeholder="请选择序号">
                  <el-option v-for="item in numberList" :key="item.key" :label="item.name" :value="item.key" />
                </el-select></div>
            </div>
          </div>
          <div class="content" v-else>
            <div class="formList">
              <div class="left">工作站：</div>
              <div class="right"> <el-select v-model="optionForm.worker" placeholder="请选择工作站">
                  <el-option v-for="(item, k) in workers" :key="item[0]" :label="k" :value="item[0]">
                    <span style="float: left; font-size: 15px">{{ k }} <i v-if="item[3] == '待重启'"
                        class="el-icon-refresh"></i> </span>
                    <span style="float: right; color: #8492a6; font-size: 15px">{{ item[1] }}</span>
                  </el-option>
                </el-select></div>
            </div>
          </div>
          <div class="bottom">
            <div class="btn" @click="confirm">
              <el-icon class="is-loading" v-if="loading">
                <Loading />
              </el-icon>
              <div>确 定</div>
            </div>
          </div>
        </div>
      </div>
    </Transition>
  </div>

</template>
<script setup lang="ts">
import { clearInterval, clearTimeout, setInterval, setTimeout } from 'worker-timers';
import dataDictionary from "@/utils/dataDictionary"
const { proxy } = getCurrentInstance() as any;
const emit = defineEmits(['returnData']);
const dic: any = dataDictionary;
const data = reactive<any>({
  optionForm: {
    worker: '',
    project: '',
    eIdx: ''
  },
  optionWindow: {
    show: false,
    type: "",
    title: "",
  },
  workers: [],
  loginName: '',
  loading: false,
  stateLoading: false,
  timerManager: {},//计时器管理
  serialNumberList: []
});

const { optionForm, optionWindow, workers, loginName, loading, stateLoading, timerManager, serialNumberList } = toRefs(data);

//打开
const open = (type: any, title: any) => {
  getWorkstation();
  optionForm.value.worker = '';
  if (type == 'add') {
    optionForm.value.project = '';
    optionForm.value.mIdx = '';
  }
  loading.value = false;
  optionWindow.value.type = type;
  optionWindow.value.title = title;
  optionWindow.value.show = true;
};

//关闭
const close = () => {
  optionWindow.value.show = false;
};

//获取工作站
const getWorkstation = async () => {
  let myInfo: any = localStorage.getItem("userInfo");
  let userInfo = JSON.parse(myInfo);
  let params: any = {
    school_id: userInfo.school_id
  };
  let res = await proxy?.$http.common.allExams(params)
  workers.value = res.workers
  loginName.value = res.login_name
  if (optionWindow.value.type == 'add') {
    getSerialNumber();
  }
};

//获取序号
const getSerialNumber = async () => {
  let params: any = new FormData();
  params.append("login_name", loginName.value);
  let res = await proxy?.$http.common.serialNumber(params)
  serialNumberList.value = res;
};

//确定
const confirm = () => {
  if (!optionForm.value.worker) {
    return false;
  }
  if (optionWindow.value.type == 'add') {
    addExamSettings();
  }
  if (optionWindow.value.type == 'close') {
    closeWorkstation();
  }
  if (optionWindow.value.type == 'restart') {
    restartWorkstation();
  }
  if (optionWindow.value.type == 'led') {
    ledWorkstation();
  }
};

//添加项目
const addExamSettings = async () => {
  let myInfo: any = localStorage.getItem("userInfo");
  let userInfo = JSON.parse(myInfo);
  let examId = optionForm.value.project + "_" + optionForm.value.mIdx;
  let params: any = {
    exam_id: examId,
    school_id: userInfo.school_id,
    wk_md5: optionForm.value.worker
  };
  loading.value = true;
  let res = await proxy?.$http.common.addExamSettings(params).finally(() => {
    loading.value = false;
  })
  if (res.status == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    close();
    emit('returnData', {});
  } else {
    proxy?.$modal.msgError(res.message);
  }
};

//关闭工作站
const closeWorkstation = async () => {
  let params: any = {
    wk_md5: optionForm.value.worker
  };
  loading.value = true;
  let res = await proxy?.$http.common.stopGpu(params).finally(() => {
    loading.value = false;
  })
  if (res.status == 200) {
    proxy?.$modal.msgSuccess('操作成功');
    close();
    emit('returnData', {});
  } else {
    proxy?.$modal.msgError(res.message);
  }
};

//重启工作站
const restartWorkstation = async () => {
  let myInfo: any = localStorage.getItem("userInfo");
  let userInfo = JSON.parse(myInfo);
  let params: any = {
    school_id: userInfo.school_id,
    wk_md5: optionForm.value.worker
  };
  loading.value = true;
  let res = await proxy?.$http.common.restartGpu(params).finally(() => {
    loading.value = false;
  })
  if (res.status == 200) {
    proxy?.$modal.msgSuccess('指令已发送，等待重启中...');
    close();
    stateLoading.value = ElLoading.service({ text: '重启中...', background: 'rgba(0, 0, 0, 0.8)' });
    getCheckWkState();
  } else {
    proxy?.$modal.msgError(res.message);
  }
};

//获取工作站状态
const getCheckWkState = async () => {
  if (timerManager.value.stateTimer == null) {
    timerManager.value.stateOutTimer = setTimeout(() => {
      getClearTimer();
      stateLoading.value?.close();
      emit('returnData', {});
      proxy?.$modal.msgError("重启超时");
    }, 23000)
  }
  let params: any = {
    wk_md5: optionForm.value.worker
  };
  loading.value = true;
  let res = await proxy?.$http.common.checkWkState(params).finally(() => {
    loading.value = false;
  })
  if (parseInt(res) > 0) {
    proxy?.$modal.msgSuccess('工作站重启成功');
    getClearTimer();
    stateLoading.value?.close();
    emit('returnData', {});
  } else {
    timerManager.value.stateTimer = setTimeout(() => {
      getCheckWkState();
    }, 2000)
  }
};

//关闭LED屏幕
const ledWorkstation = async () => {
  let myInfo: any = localStorage.getItem("userInfo");
  let userInfo = JSON.parse(myInfo);
  let params: any = {
    school_id: userInfo.school_id,
    wk_md5: optionForm.value.worker
  };
  loading.value = true;
  let res = await proxy?.$http.common.closeLedScreen(params)
  if (res.status == 200) {
    proxy?.$modal.msgSuccess('指令已发送，等待LED关闭中...');
    close();
    loading.value = false;
    emit('returnData', {});
  } else {
    proxy?.$modal.msgError(res.message);
    loading.value = false;
  }
};

/**
 * 清空定时任务
*/
const getClearTimer = (data?: any) => {
  if (data) {
    //清除指定
    clearInterval(timerManager.value[data])
    timerManager.value[data] = null;
  } else {
    //清除全部
    for (let key in timerManager.value) {
      if (timerManager.value.hasOwnProperty(key)) {
        clearInterval(timerManager.value[key])
        timerManager.value[key] = null;
      }
    }
  }
};

/**
 * 获取项目列表
*/
const projectList = computed(() => {
  let list = [];
  let project = dic.project;
  for (let key in project) {
    if (project.hasOwnProperty(key)) {
      list.push({
        key: key,
        name: project[key]
      })
    }
  }
  return list;
});

/**
 * 获取序号列表
*/
const numberList = computed(() => {
  let list = [];
  let num = Number(serialNumberList.value[optionForm.value.project])
  for (let i = 1; i <= num; i++) {
    list.push({
      key: i,
      name: i
    })
  }
  return list;
});


/**
 * 获取极限值
*/
const eMaxId = computed(() => {
  let num = Number(serialNumberList.value[optionForm.value.project])
  return num;
});

onMounted(() => {
})

onBeforeUnmount(() => {
  loading.value = false;
})

//暴露给父组件用
defineExpose({
  open,
  close,
  optionWindow
})
</script>
<style lang="scss" scoped>
.mask {
  position: fixed;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.78);
  z-index: 998;
}

.optionWindow {
  position: fixed;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #FFFFFF;
  z-index: 999;

  .box {
    width: 50%;
    border-radius: 1.6rem;
    background: linear-gradient(60deg, #092941 -85%, #2A484B 96%);
    box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.3);
    padding: 20px;

    .top {
      color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 1.93rem;
        color: #13ED84;
      }

      .close {}
    }

    .content {
      max-height: 65vh;
      margin-bottom: 2vh;

      .formList {
        display: flex;
        align-items: center;
        padding: 1.2vh 0;

        .left {
          flex-shrink: 0;
          font-size: 1rem;
        }

        .left1 {
          width: 8rem;
        }

        .right {
          width: 100%;
        }
      }

    }

    .bottom {
      height: 3.59rem;
      padding: 2.5rem 0 0 0;
      align-items: center;
      color: #ffffff;
      display: flex;
      justify-content: space-around;
      position: relative;
      z-index: 2;

      .btn {
        width: 33%;
        height: 3.59rem;
        line-height: 3.59rem;
        font-size: 2rem;
        margin: 0 auto;
        border-radius: 0.83rem;
        font-size: 2rem;
        text-align: center;
        color: #1A293A;
        background: radial-gradient(141% 126% at 5% 93%, #8EFFA9 0%, #07FFE7 100%);
        box-shadow: inset 0px 1px 0px 2px rgba(255, 255, 255, 0.3);
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;

        .is-loading {
          margin-right: 5px;
        }
      }
    }

    .boxBg {
      width: 100%;
      height: 100%;
      display: block;
      background-position: center center;
      background-repeat: no-repeat;
      background-size: contain;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;
      opacity: 0.1;
    }
  }
}
</style>
