<template>
  <div class="config">
    <Header @confirmExit="confirmExit"></Header>
    <div class="main">
      <el-table :data="examList" class="table" @row-click="handleSelectionChange" highlight-current-row>
        <el-table-column prop="0" label="项目" sortable />
        <el-table-column prop="1" label="状态" />
        <el-table-column prop="2" label="工作站" :formatter="showWorkers" sortable />
        <el-table-column fixed="right" label="操作" width="210">
          <template #default="scope">
            <el-button @click="chooseItem(scope.row)" size="small" type="primary" plain>部署</el-button>
            <el-button @click="delExamConf(scope.row)" size="small" type="danger" plain>删除</el-button>
            <el-button @click="closeExam(scope.row)" size="small" type="warning" plain v-show="scope.row[1] == '已开启'">下课 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footerBtn">
      <div class="btn" @click="openWorkstation('add', '添加项目')">添加项目</div>
      <div class="btn" @click="openWorkstation('led', '关闭LED屏幕')">关闭LED屏幕</div>
      <div class="btn" @click="openWorkstation('restart', '重启工作站')">重启工作站</div>
      <div class="btn" @click="openWorkstation('close', '关闭工作站')">关闭工作站</div>
      <div class="btn" @click="getExamList">刷新</div>
    </div>
    <WorkstationWindow ref="workstationWindowRef" @returnData="returnRefresh" />
  </div>
</template>

<script setup name="SetConfig" lang="ts">
import dataDictionary from '@/utils/dataDictionary';
const { proxy } = getCurrentInstance() as any;
const router = useRouter();
const dic: any = dataDictionary;
const workstationWindowRef = ref();

const data = reactive<any>({
  examList: [],
  selectValue: [],
  loginname: '',
  workers: {},
  workerMap: [],
  oLWorkers: {},
  examMaxIdxMap: {},
  existExamIds: {}
});

const { examList, selectValue, loginname, workers, workerMap, oLWorkers, examMaxIdxMap, existExamIds } = toRefs(data);

//被选行
const handleSelectionChange = (data: any) => {
  selectValue.value = data;
};

//获取列表
const getExamList = 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;
  Object.keys(res.workers).forEach((item) => {
    workerMap.value[res.workers[item][0]] = item;
    let wkVal = workers.value[item];
    if (wkVal[1] === '在线') {
      oLWorkers.value[item] = wkVal;
    }
  });
  loginname.value = res.login_name;
  let list = [];
  for (let i in res.exams) {
    if (i.indexOf('skiprope') != 0 && i.indexOf('heartbeat') != 0) {
      let enIndex = i.split('_');
      let en = enIndex[0];
      let eindex = enIndex[1];
      res.exams[i].worker.forEach((worker: any) => {
        if (worker in examMaxIdxMap.value) {
        } else {
          examMaxIdxMap.value[worker] = {};
        }
        if (en in examMaxIdxMap.value[worker]) {
          if (Number(eindex) > Number(examMaxIdxMap.value[worker][en])) {
            examMaxIdxMap.value[worker][en] = Number(eindex);
          }
        } else {
          examMaxIdxMap.value[worker][en] = Number(eindex);
        }
        if (worker in existExamIds.value) {
          existExamIds.value[worker].push(i);
        } else {
          existExamIds.value[worker] = [];
        }
      });
      list.push([dic.project[en] + '_' + eindex, res.exams[i].isopen, res.exams[i].worker, i]);
    }
  }
  examList.value = list;
};

//转换
const showWorkers = (row: any) => {
  return row[2].join(',');
};

//操作工作站
const openWorkstation = (type: any, title: any) => {
  workstationWindowRef.value.open(type, title);
};

//部署
const chooseItem = (item: any) => {
  // let itemName = this.exams[item]
  let isOn = false;
  item[2].forEach((wkId: any) => {
    if (workers.value[wkId]) {
      if (workers.value[wkId][1] == '在线') {
        isOn = true;
      }
    }
  });
  if (isOn) {
    router.push({
      path: '/set/deploy',
      query: { examId: item[3] }
    });
  } else {
    proxy?.$modal.msgError(`工作站不在线暂不允许配置`);
  }
};

//删除项目
const delExamConf = (item: any) => {
  let conTitle = `是否移除项目-${item[0]}`;
  proxy?.$modal
    .confirm(conTitle)
    .then(() => {
      let examId = item[3];
      let ename = examId.split('_')[0];
      let eidx = Number(examId.split('_')[1]);

      let myInfo: any = localStorage.getItem('userInfo');
      let userInfo = JSON.parse(myInfo);
      let params: any = {
        exam_id: examId,
        school_id: userInfo.school_id
      };
      proxy?.$http.common.delExamSettings(params).then((res: any) => {
        if (res.status == 200) {
          let selWorker: any;
          let existIdx: any;
          item[2].forEach((worker: any) => {
            existIdx = existExamIds.value[worker].indexOf(examId);
            if (examMaxIdxMap.value[worker][ename] == eidx) {
              examMaxIdxMap.value[worker][ename] = eidx - 1;
              selWorker = worker;
            } else if (existIdx > -1) {
              selWorker = worker;
            }
          });
          console.log(selWorker, examMaxIdxMap.value, 'examMaxIdxMap.value');
          // let existIdx = existExamIds.value[selWorker].indexOf(examId)
          let index = examList.value.indexOf(item);
          if (existIdx > -1) {
            existExamIds.value[selWorker].splice(existIdx, 1);
          }
          if (index > -1) {
            examList.value.splice(index, 1);
          }
          proxy?.$modal.msgSuccess(`删除成功`);
        } else {
          proxy?.$modal.msgError(`${res.message}`);
        }
      });
    })
    .catch((err: any) => {});
};

// 下课
const closeExam = (item: any) => {
  let myInfo: any = localStorage.getItem('userInfo');
  let userInfo = JSON.parse(myInfo);
  let params: any = {
    exam_id: item[3],
    school_id: userInfo.school_id
  };
  proxy?.$http.common.closeExamForce(params).then((res: any) => {
    if (res.status == 200) {
      proxy?.$modal.msgSuccess(`下课成功`);
    }
    getExamList();
  });
};

/**
 * 返回刷新列表
 */
const returnRefresh = () => {
  getExamList();
};

/**
 * 返回
 */
const confirmExit = () => {
  router.go(-1);
};

onMounted(() => {
  getExamList();
});

onActivated(() => {
  getExamList();
});
</script>

<style lang="scss" scoped>
$topPadding: 5.19rem;
$waiPadding: 6.51rem;

.main {
  width: calc(100% - ($waiPadding * 2));
  padding-top: 10rem;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  overflow: hidden;

  .table {
    width: 100%;
    height: 65vh;
  }
}

.footerBtn {
  width: 100%;
  padding: 0 calc(13.02rem / 2);
  box-sizing: border-box;
  position: fixed;
  bottom: 3vh;
  display: flex;
  justify-content: flex-end;

  .btn {
    width: 11vw;
    height: 6.1vh;
    line-height: 6.1vh;
    font-size: 3vh;
    color: #1a293a;
    text-align: center;
    border-radius: 1vh;
    cursor: pointer;
    background: radial-gradient(159% 126% at 5% 93%, #8effa9 0%, #07ffe7 100%);
    box-shadow: 3px 6px 4px 1px rgba(0, 0, 0, 0.1874), inset 0px 1px 0px 2px rgba(255, 255, 255, 0.3);
    margin-left: 10px;

    &:hover {
      background: #8effa9;
    }
  }
}
</style>
