<template>
  <div class="bg" style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: center; overflow: hidden">
    <a-spin :spinning="loading" />

    <div id="fanLocal3D" style="width: 100%; height: 100%; position: absolute; overflow: hidden"> </div>
    <div id="fanLocal3DCSS" class="threejs-Object-CSS" style="width: 100%; height: 100%; position: absolute; overflow: hidden">
      <div style="z-index: -1; position: relative">
        <div class="elementTag" id="inputBox">
          <div class="elementContent">
            <p>风筒入口风速：{{ selectData.windSpeed1 ? selectData.windSpeed1 : '-' }}</p>
            <p>风筒入口瓦斯浓度 {{ selectData.gas1 ? selectData.gas1 : '-' }}</p>
          </div>
        </div>
        <div class="elementTag" id="outBox">
          <div class="elementContent elementContent-r">
            <p>迎头供风量：{{ selectData.windQuantity1 ? selectData.windQuantity2 : '-' }}</p>
            <p>迎头瓦斯浓度：{{ selectData.gas1 ? selectData.gas1 : '-' }}</p>
          </div>
        </div>
        <div class="elementTag" id="returnBox">
          <div class="elementContent">
            <p>回风流瓦斯浓度：{{ selectData.gas3 ? selectData.gas3 : '-' }}</p>
          </div>
        </div>
        <div class="elementTag" id="gateBox">
          <div class="elementContent">
            <p>风门状态：关</p>
            <p>风门过风面积：{{ selectData.gas1 ? selectData.gas1 : '-' }}</p>
          </div>
        </div>
        <div  class="elementTag" id="windownBox">
          <div class="elementContent">
            <p>风窗全风压回风流：0</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="scene-box">
    <div class="top-box">
      <div class="top-center row">
        <div class="button-box" v-for="(item, index) in modalTypeArr.leftBtnArr" :key="index" @click="showModal(item)">{{ item.value }}</div>
      </div>
      <div class="top-right row">
        <div class="button-box" v-for="(item, index) in modalTypeArr.rightBtnArr" :key="index" @click="showModal(item)">{{ item.value }}</div>
      </div>
    </div>
    <div class="title-text">
      {{ selectData.stationname }}
    </div>
    <div class="bottom-tabs-box">
      <a-tabs class="tabs-box" v-model:activeKey="activeKey" @change="tabChange">
        <a-tab-pane key="1" tab="实时监测">
          <GroupMonitorTable :dataSource="dataSource" columnsType="fanlocal_monitor" @selectRow="getSelectRow" />
          <!-- <MonitorTable
            columnsType="fanlocal_monitor"
            :dataSource="dataSource"
            @selectRow="getSelectRow"
            design-scope="fanlocal-monitor"
            title="局部通风机监测"
          /> -->
        </a-tab-pane>
        <a-tab-pane key="2" tab="实时曲线图" force-render>
          <div class="tab-item" v-if="activeKey === '2'">
            <div class="vent-flex-row-between" style="height: 100%">
              <BarSingle
                :xAxisData="[
                  { key: 'T1', valueKey: 'gas1' },
                  { key: 'T2', valueKey: 'gas2' },
                  { key: 'T3', valueKey: 'gas3' },
                  { key: 'T4', valueKey: 'gas4' },
                ]"
                :dataSource="dataSource[selectRowIndex]"
                height="100%"
                :chartsColumns="chartsColumns"
                style="flex: 3"
              />
              <BarSingle
                :xAxisData="[
                  { key: 'F1', valueKey: 'windQuantity1' },
                  { key: 'F2', valueKey: 'windQuantity2' },
                ]"
                :dataSource="dataSource[selectRowIndex]"
                height="100%"
                :chartsColumns="chartsColumns1"
                style="flex: 2"
              />
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="历史数据">
          <div class="tab-item">
            <HistoryTable columns-type="fanlocal_history" device-type="fanlocal" :device-list-api="baseList" designScope="fanlocal-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="4" tab="报警历史">
          <div class="tab-item">
            <AlarmHistoryTable columns-type="alarm_history" device-type="fanlocal" :device-list-api="baseList" designScope="alarm-history" />
          </div>
        </a-tab-pane>
        <a-tab-pane key="5" tab="操作历史">
          <div class="tab-item">
            <HandlerHistoryTable columns-type="operatorhistory" device-type="fanlocal" :device-list-api="baseList" designScope="alarm-history" />
          </div>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <div style="z-index: -1; position: absolute; top: 50px; right: 10px; width: 300px; height: 280px; margin: auto" class="player1">
    <LivePlayer id="jb-player1" ref="player1" :videoUrl="flvURL1()" muted live loading controls />
  </div>
  <a-modal v-model:visible="modalIsShow" :title="modalTitle" @ok="handleOk">
    <div class="modal-container">
      <div class="vent-flex-row">
        <ExclamationCircleFilled style="color: #ffb700; font-size: 30px" />
        <div class="warning-text">您是否要进行{{ modalTitle }}操作？</div>
      </div>
      <div class="" v-if="modalType == 'startSmoke'">
        <div class="startSmoke-select">
          <div class="label">1#风机：</div>
          <a-radio-group v-model:value="mainWindIsShow1" @change="changeMotor" name="localWind1">
            <a-radio value="open">开启</a-radio>
            <a-radio value="stop">停止</a-radio>
          </a-radio-group>
        </div>
        <div class="startSmoke-select">
          <div class="label">2#风机：</div>
          <a-radio-group v-model:value="mainWindIsShow2" @change="changeMotor" name="localWind2">
            <a-radio value="open">开启</a-radio>
            <a-radio value="stop">停止</a-radio>
          </a-radio-group>
        </div>
      </div>
      <!-- 调频 -->
      <div class="vent-flex-row input-box" v-if="modalType == 'frequency'">
        <div class="label">运行频率（单位）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="30" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'needAir'">
        <div class="label">需风量（单位）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="30" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'disAirAlarm'">
        <div class="label">漏风率（%）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'diameter'">
        <div class="label">风筒直径（m）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'len'">
        <div class="label">风筒长度（m）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'windPowerLimit'">
        <div class="label">风电闭锁限值（m³/min）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <div class="vent-flex-row input-box" v-if="modalType == 'gasPowerLimit'">
        <div class="label">瓦斯电闭锁限值（m³/min）：</div>
        <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
      </div>
      <div v-if="modalType == 'gasAlarm'">
        <div class="vent-flex-row input-box">
          <div class="label">传感器名称：</div>
          <a-select placeholder="传感器" @change="handleChangeSensor" :options="sensorList" v-model:value="modalSensor" />
        </div>
        <div class="vent-flex-row input-box">
          <div class="label">传感器值：</div>
          <a-input-number size="small" v-model:value="frequencyVal" :min="0" :max="50" :step="0.1" />
        </div>
      </div>
      <div v-if="modalType == 'airVolumeAlarm'">
        <div class="vent-flex-row input-box">
          <div class="label">风量上限（m³/min）：</div>
          <a-input-number size="small" v-model:value="modalTypeArr.rightBtnArr[3].min" :min="0" :max="50" :step="0.1" />
        </div>
        <div class="vent-flex-row input-box">
          <div class="label">风量下限（m³/min）：</div>
          <a-input-number size="small" v-model:value="modalTypeArr.rightBtnArr[3].max" :min="0" :max="50" :step="0.1" />
        </div>
      </div>
      <!-- 启动或停止 -->
      <div class="" v-if="modalType == 'startSmoke'"> </div>
      <div class="vent-flex-row input-box">
        <div class="label">操作密码：</div>
        <a-input size="small" type="password" v-model:value="passWord" />
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { ExclamationCircleFilled } from '@ant-design/icons-vue';
  import { onBeforeMount, ref, onMounted, nextTick, toRaw, reactive, onUnmounted } from 'vue';
  import BarSingle from '../../../../components/chart/BarSingle.vue';
  import GroupMonitorTable from '../comment/GroupMonitorTable.vue';
  import HistoryTable from '../comment/HistoryTable.vue';
  import AlarmHistoryTable from '../comment/AlarmHistoryTable.vue';
  import HandlerHistoryTable from '../comment/HandlerHistoryTable.vue';
  import { mountedThree, setModelType, destroy, addCssText, addText, playSmoke } from './fanLocal.three';
  import lodash from 'lodash';
  import { getTableList, list } from '/@/views/vent/monitorManager/fanLocalMonitor/fanLocal.api';
  import { list as baseList } from '../../deviceManager/fanTabel/fan.api';
  import { chartsColumns, chartsColumns1 } from './fanLocal.data';
  import { deviceControlApi } from '/@/api/vent/index';
  import LivePlayer from '@liveqing/liveplayer-v3';
  import { message } from 'ant-design-vue';

  const modalTypeArr = reactive({
    leftBtnArr: [
      {
        key: 'startSmoke',
        value: '启动风机',
      },
      {
        key: 'changeSmoke',
        value: '一键倒机',
      },
      {
        key: 'windPower',
        value: '风电闭锁',
      },
      {
        key: 'gasPower',
        value: '瓦斯电闭锁',
      },
      {
        key: 'needAir',
        value: '需风量',
      },
      {
        key: 'diameter',
        value: '风筒直径',
      },
      {
        key: 'len',
        value: '风筒长度',
      },
    ],
    rightBtnArr: [
      {
        key: 'frequency',
        value: '调频',
      },
      {
        key: 'windPowerLimit',
        value: '风电闭锁限值',
      },
      {
        key: 'gasPowerLimit',
        value: '瓦斯电闭锁限值',
      },
      {
        key: 'airVolumeAlarm',
        value: '风量报警',
        min: 0,
        max: 100,
      },
      {
        key: 'disAirAlarm',
        value: '漏风率报警',
      },
      {
        key: 'gasAlarm',
        value: '瓦斯报警',
      },
    ],
  });
  const sensorList = ref<any[]>([
    {
      value: '1',
      label: 'T1',
    },
    {
      value: '2',
      label: 'T2',
    },
    {
      value: '3',
      label: 'T3',
    },
  ]);
  const modalSensor = ref(null);
  const loading = ref(false);
  const activeKey = ref('1');
  const player1 = ref();
  const modalIsShow = ref<boolean>(false); // 是否显示模态框
  const modalTitle = ref(''); // 模态框标题显示内容，根据设备操作类型决定
  const modalType = ref(''); // 模态框内容显示类型，设备操作类型
  const frequencyVal = ref(40); //频率
  const mainWindIsShow1 = ref('open'); // 1#风机默认启动
  const mainWindIsShow2 = ref('stop'); // 2#风机默认不启动
  const passWord = ref('');
  // 默认初始是第一行
  const selectRowIndex = ref(0);
  // 设备数据
  const controlType = ref(1);
  // 监测数据
  const initData = {
    deviceID: '',
    deviceType: '',
    strname: '',
    dataDh: '-', //压差
    dataDtestq: '-', //测试风量
    sourcePressure: '-', //气源压力
    dataDequivalarea: '-',
    netStatus: '0', //通信状态
    fault: '气源压力超限',
  };
  const flvURL1 = () => {
    // return `https://sf1-hscdn-tos.pstatp.com/obj/media-fe/xgplayer_doc_video/flv/xgplayer-demo-360p.flv`;
    return ''
  };
  // 监测数据
  const selectData = reactive(lodash.cloneDeep(initData));
  // const dataSource = computed(() => {
  //   const data = [...getRecordList()] || [];
  //   Object.assign(selectData, toRaw(data[selectRowIndex.value]));
  //   return data;
  // });
  const tabChange = (activeKeyVal) => {
    activeKey.value = activeKeyVal;
  };

  const dataSource = ref([]);

  //
  async function getDataSource(){
    const res = await list({ devicetype: 'fanlocal', pagetype: 'normal' });
    const dataArr = res.msgTxt[0].datalist || [];
    dataSource.value = [];
    dataArr.forEach((data) => {
      const readData = data.readData;
      data = Object.assign(data, readData);
      dataSource.value.push(data);
    });
    const data: any = toRaw(dataSource.value[selectRowIndex.value]); //maxarea
    return data;
  };

  // https获取监测数据
  let timer: null | NodeJS.Timeout = null;
  function getMonitor() {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(async () => {
        await getDataSource();
        Object.assign(selectData, deviceBaseList.value, dataSource.value[selectRowIndex.value]);
        addText(selectData);
        // playAnimation(data, selectData.maxarea);
        if (timer) {
          timer = null;
        }
        getMonitor();
      }, 1000);
    }
  };

  // 获取设备基本信息列表
  const deviceBaseList = ref([]);
  function getDeviceBaseList() {
    getTableList({ pageSize: 1000 }).then((res) => {
      deviceBaseList.value = res.records;
    });
  };

  // 切换检测数据
  function getSelectRow(id) {
    if (!id) return;
    loading.value = true;
    const baseDataIndex: any = dataSource.value.findIndex((baseData: any) => baseData.deviceID === id);
    selectRowIndex.value = baseDataIndex;
    const type = baseDataIndex > 0 ? 'fm' : 'fc';
    setModelType(type).then(() => {
      loading.value = false;
    });
    const data = dataSource.value[baseDataIndex];
    // mainWindIsShow1.value = 'stop';
    // mainWindIsShow2.value = 'stop';
    if (data['fanStart1'] == 1) {
      mainWindIsShow1.value = 'open';
      mainWindIsShow2.value = 'stop';
    } else if (data['fanStart2'] == 1) {
      mainWindIsShow2.value = 'open';
      mainWindIsShow1.value = 'stop';
    }
    addCssText(selectRowIndex.value);
    return;
  };

  // 打开并设置modal的标题
  function showModal(obj) {
    modalType.value = obj.key;
    modalTitle.value = obj.value;
    modalIsShow.value = true;
  };

  function changeMotor(e){
    const target = e.target;
    if (target.name === 'localWind1') {
      if (target.value === 'open') {
        mainWindIsShow2.value = 'stop';
      }
    } else if (target.name === 'localWind2') {
      if (target.value === 'open') {
        mainWindIsShow1.value = 'stop';
      }
    }
  };

  function handleOk(e: MouseEvent) {
    if (passWord.value !== '123456') {
      message.warning('密码不正确，请重新输入');
      return;
    }

    const handType = modalType.value;
    const frequency = frequencyVal.value;
    const data = {
      deviceid: selectData.deviceID,
      devicetype: 'fanlocal_systeml_zj',
      paramcode: '',
      value: null,
    };
    if (handType === 'startSmoke') {
      console.log(mainWindIsShow1.value, mainWindIsShow2.value);

      // 启动风机
      if (mainWindIsShow1.value === 'open' && mainWindIsShow2.value === 'stop') {
        playSmoke(handType, 'top', frequency, 'open');
        data.paramcode = 'fanRun1';
        deviceControlApi(data).then((res) => {
          console.log('设备操作结果', res);
        });
      } else if (mainWindIsShow2.value === 'open' && mainWindIsShow1.value === 'stop') {
        playSmoke(handType, 'down', frequency, 'open');
        data.paramcode = 'fanRun2';
        deviceControlApi(data).then((res) => {
          console.log('设备操作结果', res);
        });
      } else if (mainWindIsShow1.value === 'stop' && mainWindIsShow2.value === 'stop') {
        playSmoke(handType, '', frequency, 'stop');
      }
    } else if (handType === 'frequency') {
      // 调频
      playSmoke(handType, 'top', frequency, '');
      if (mainWindIsShow1.value === 'open') {
        data.paramcode = 'power1';
      } else if (mainWindIsShow2.value === 'open') {
        data.paramcode = 'power2';
      }
      data.value = frequency;
      deviceControlApi(data).then((res) => {
        console.log('设备操作结果', res);
      });
    } else if (handType === 'changeSmoke') {

      // 一键倒机
      if (mainWindIsShow1.value === 'open' && mainWindIsShow2.value === 'stop') {
        playSmoke('startSmoke', 'down', frequency, 'open');
        data.paramcode = 'fanRun2';
        deviceControlApi(data).then((res) => {
          console.log('设备操作结果', res);
        });
        mainWindIsShow1.value = 'stop';
        mainWindIsShow2.value = 'open';
      } else if (mainWindIsShow2.value === 'open' && mainWindIsShow1.value === 'stop') {
        playSmoke('startSmoke', 'top', frequency, 'open');
        data.paramcode = 'fanRun1';
        deviceControlApi(data).then((res) => {
          console.log('设备操作结果', res);
        });
        mainWindIsShow1.value = 'open';
        mainWindIsShow2.value = 'stop';
      } else if (mainWindIsShow1.value === 'stop' && mainWindIsShow2.value === 'stop') {
        playSmoke(handType, '', frequency, 'stop');
      }
    }
    modalTitle.value = '';
    modalIsShow.value = false;
  };

  function handleChangeSensor(value: string){
    console.log(value);
  };

  function addPlayVideo() {
    if (player1.value && player1.value.play) {
      if (!player1.value.paused()) player1.value.play();
      document.body.removeEventListener('mousedown', addPlayVideo);
    }
  };

  onBeforeMount(() => {
    getDeviceBaseList();
  });

  onMounted(() => {
    // loading.value = true;
    mountedThree(player1.value).then(() => {
      nextTick(() => {
        getMonitor();
        // addCssText(selectRowIndex.value);

        playSmoke('startSmoke', 'top', frequencyVal.value, 'open');
      });
    });
    document.body.addEventListener('mousedown', addPlayVideo, false);
  });

  onUnmounted(() => {
    destroy();
    if (timer) {
      clearTimeout(timer);
      timer = undefined;
    }
  });
</script>
<style scoped lang="less">
  @import '/@/design/vent/modal.less';
  :deep(.@{ventSpace}-tabs-tabpane-active) {
    overflow: auto;
  }
  .input-box {
    display: flex;
    align-items: center;
    .input-title {
      color: #73e8fe;
      width: auto;
    }
    margin-right: 10px;
  }
  .label {
    max-width: 220px;
  }
  .@{ventSpace}-input {
    width: 150px;
  }
</style>
