<template>
  <a-modal :visible="isShowPage" width="80%" style="top: 20px" title="详情" :ok-button-props="{ style: { display: 'none' } }" cancelText="关闭" @cancel="() => (isShowPage = false)">
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
       <!--操作栏-->
       <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
  </a-modal>
</template>

<script lang="ts" name="jiaoshi-kcJiaoshirongliangSfyc" setup>
  import {ref, computed, unref, Ref, nextTick } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage'
  import { columns, searchFormSchema } from './KcZhihuijiaoshiStateLog.data';
  import { list } from './KcZhihuijiaoshiStateLog.api';
import { defHttp } from '/@/utils/http/axios';
import videojs from "video.js";
import { useMessage } from '/@/hooks/web/useMessage';

  const queryParam:any = ref({});

  const checkedKeys = ref<Array<string | number>>([]);
  //注册model
  const [registerModal, { openModal }] = useModal();
const { createMessage, createInfoModal, createErrorModal,createConfirm } = useMessage();
  //注册table数据
  const { tableContext } = useListPage({
    tableProps:{
      title: '教室容量',
      api: list,
      columns,
      canResize:false,
      showActionColumn: true,
      immediate: false,
      formConfig: {
        //labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter:true,
        showAdvancedButton:true,
        fieldMapToNumber: [
        ],
        fieldMapToTime: [
        ],
      },
      beforeFetch: (params) => {
        params.column = '',params.order = '';//新生成的默认不带排序
        return Object.assign(params, queryParam.value);
      },
      actionColumn: {
        width: 180,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: undefined,
      },
    },
  })

  const [registerTable, { reload },{ rowSelection, selectedRowKeys }] = tableContext

  const isShowPage:Ref<boolean> = ref(false);

   /**
    * 详情
   */
   function handleDetail(record: Recordable) {
     openModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
   }
   /**
    * 操作栏
    */
    function getTableAction(record){
      if(record.forceState === 'green'){
        return [
         {
           label: '检测教室',
           onClick: jcZhiHuiJiaoShi.bind(null, record),
         },
         {
           label: '标记为无效',
           onClick: changeFlag.bind(null, record,"red"),
         }
       ]
      }else{
        return [
         {
           label: '检测教室',
           onClick: jcZhiHuiJiaoShi.bind(null, record),
         },
         {
           label: '标记为有效',
           onClick: changeFlag.bind(null, record,"green"),
         }
       ]
      }
       
   }

   
//检查智慧教室
async function jcZhiHuiJiaoShi(record){
  console.log(`🚀 ~ jcZhiHuiJiaoShi ~ record:`, record)
  let jxlMap = {};
  let getListAction:any = [];
  let liveIsExist = (x) => {
    return new Promise((resolve,reject) => {
      videojs.xhr.get(x.pullUrl,(err, resp, body) => {
        if(err){
          reject(x);
          x.isOnLine = false
        }else{
          resolve(x);
          x.isOnLine = true
        }
      })
    })
  }

  let child = [];

  await defHttp.get({url: '/jiaoshi/kcZhihuijiaoshi/list',params:{jsbh:record.jsbh}}).then((res:any) => {
    console.log(`🚀 ~ awaitdefHttp.get ~ res:`, res)
    console.log(`🚀 ~ awaitdefHttp.get ~ res:`, res.records)
    child = res.records;
  })

  
  Object.values(child).forEach(item => {
    let x:any = item;
    if(x.pullUrl){
      getListAction.push(liveIsExist(x));
    }
  });
  console.log(`🚀 ~ Object.values ~ getListAction:`, getListAction)
  Promise.all(getListAction).then(resList => {
  }).catch((e) => {
    console.error(`🚀 ~ file: index.vue:1170 ~ Promise.all Error ~ ress:`, e);
  }).finally((...d) => {
    console.log("正常执行！",...d);
    //弹出成功或失败
    let isSuccess = true;
    let msgList:any = [];
    Object.values(child).forEach(item => {
      let _item = item as any;
      console.log(`🚀 ~ Object.values ~ _item:`, _item)
      if(_item.isOnLine){
        msgList.push(_item.xm + '：连接成功！');
      }else{
        msgList.push(_item.xm + '：连接失败！');
        isSuccess = false;
      }
    });
    if(msgList.length){
      if(isSuccess){
        createInfoModal({ title: '成功！', content: msgList.join(',') });
      }else{
        createErrorModal({ title: '失败！', content: msgList.join(',') });
      }
    }
  });
}

  //标记是否有效
  function changeFlag(record, flag){
    record.forceState = flag;
    defHttp.post({ url: '/jiaoshi/kcZhihuijiaoshiStateLog/updateByJsbh', params: {
      jsbh: record.jsbh,
      forceState: flag
    }}).then(res => {
      queryParam.value.jxlName = null;
      loadData();
    });
  }

  function open(param){
    console.log(`🚀 ~ detaillogopen ~ param:`, param)
    nextTick(() => {
      queryParam.value = Object.assign({ }, param);
      reload();
      isShowPage.value = true;
      setTimeout(() => {
        reload();
      }, 100);
    });
  }

  function close(){
    isShowPage.value = false;
  }

   /**
    * 成功回调
    */
  function handleSuccess() {
      (selectedRowKeys.value = []) && reload();
   }

   defineExpose({
    open,
    close,
   });


</script>

<style scoped>

</style>