<template>
  <a-spin tip="Loading..." :spinning="loading">
    <div class="monitor-container">
      <div class="lr left-box">
        <ventBox1>
          <template #title>
            <div>均压与低氧参数监测与设置</div>
          </template>
          <template #container>
            <div class="vent-flex-row-between auto-control mt-10px mb-10px">
              <div class="title">自动调节：</div>
              <a-radio-group :value="avePressSetting.isAutoControl" name="radioGroup" @change="changeIsAutoControl">
                <a-radio value="1">关闭</a-radio>
                <a-radio value="2">开启</a-radio>
              </a-radio-group>
            </div>
            <div class="input-box">
              <!-- <div class="divider-line">开始条件</div>
              <div v-for="(item, index) in settingParam1" class="input-item" :key="index">
                <div class="title">{{ item.title }}：</div>
                <a-input-number class="input-value" v-model:value="formData[item.code]" placeholder="" />
                <div class="unit">{{ item.unit }}</div>
              </div> -->
              <div class="divider-line">调节参数</div>
              <div v-for="(item, index) in settingParam4" class="input-item" :key="index">
                <div class="title">{{ item.title }}：</div>
                <a-input-number class="input-value" v-model:value="avePressSetting[item.code]" placeholder="" :disabled="settingFormDisabled" />
                <div class="unit">{{ item.unit }}</div>
              </div>
              <!-- <div class="divider-line">结束时间</div>
              <div v-for="(item, index) in settingParam3" class="input-item" :key="index">
                <div class="title">{{ item.title }}：</div>
                <a-input-number class="input-value" v-model:value="formData[item.code]" placeholder="" />
                <div class="unit">{{ item.unit }}</div>
              </div> -->
            </div>
            <div class="btn-box flex" style="text-align: center">
              <div class="btn btn1 flex-1" @click="editSettingForm">{{ settingFormDisabled ? '编辑' : '取消' }}</div>
              <div class="btn btn1 flex-1" @click="submitSettingForm">提交</div>
            </div>
          </template>
        </ventBox1>
      </div>
      <div class="lr">
        <ventBox1>
          <template #title>
            <div>均压工作面风机与风门联动</div>
          </template>
          <template #container>
            <div class="vent-flex-row-between auto-control mt-10px mb-10px">
              <div class="title">自动调节：</div>
              <a-radio-group :value="avePressLinkage.isAuto" name="radioGroup" @change="changeIsAuto">
                <a-radio :value="false">关闭</a-radio>
                <a-radio :value="true">开启</a-radio>
              </a-radio-group>
            </div>
            <div class="btn-box" style="text-align: center">
              <div class="btn btn1" @click="() => openModal()">控制密码修改</div>
            </div>
          </template>
        </ventBox1>
      </div>
      <ModuleCommon
        v-for="cfg in configs"
        :key="cfg.deviceType"
        :show-style="cfg.showStyle"
        :module-data="cfg.moduleData"
        :module-name="cfg.moduleName"
        :device-type="cfg.deviceType"
        :data="selectData"
        :visible="true"
      />
    </div>
    <PasswordModal :modal-is-show="modalVisible" modal-title="提交" @handle-ok="handleResolve" />
    <UpdatePassword @register="updatePwdRegister" @submit="handleChangePassword" />
  </a-spin>
</template>
<script setup lang="ts">
  import { ref, onMounted, onUnmounted, defineProps } from 'vue';
  import { mountedThree, destroy, setModelType, updateText, play } from '../balancePress.threejs';
  import { list } from '../balancePress.api';
  import ModuleCommon from '../../../home/configurable/components/ModuleCommon.vue';
  import { useInitConfigs } from '../../../home/configurable/hooks/useInit';
  import { useGlobSetting } from '/@/hooks/setting';
  import { settingParam4 } from '../balancePress.data';
  import { notification } from 'ant-design-vue';
  import ventBox1 from '/@/components/vent/ventBox1.vue';
  import PasswordModal from '../../comment/components/PasswordModal.vue';
  import UpdatePassword from '../../comment/components/UpdatePassword.vue';
  import { useModal } from '/@/components/Modal';
  import { connectWebSocket, onWebSocket } from '/@/hooks/web/useWebSocket';
  import { getToken } from '/@/utils/auth';
  import { useUserStore } from '/@/store/modules/user';
  import { usePressControl } from '../hooks/useControl';
  // import { Config } from '../../../deviceManager/configurationTable/types';

  const props = defineProps({
    deviceId: {
      type: String,
      require: true,
    },
  });

  const { sysOrgCode } = useGlobSetting();

  const loading = ref(false);

  // 监测数据
  const selectData = ref();

  // https获取监测数据
  let timer: any = null;
  function getMonitor(flag?) {
    if (Object.prototype.toString.call(timer) === '[object Null]') {
      timer = setTimeout(
        async () => {
          if (props.deviceId) {
            const data = await getDataSource(props.deviceId);
            // Object.assign(selectData, data);
            updateText(selectData);
            selectData.value = data;
          }
          if (timer) {
            timer = null;
          }
          await getMonitor();
        },
        flag ? 0 : 1000
      );
    }
  }

  async function getDataSource(systemID) {
    const res = await list({ devicetype: 'sys', systemID });

    const result = Array.from(res.msgTxt).reduce(
      (obj: any, e: any) => {
        obj[e.type] = e;

        // if (true) {
        if (sysOrgCode === 'sdmtjtswmk') {
          if (e.type.startsWith('fanlocal')) {
            obj.fanlocal.datalist.push(...e.datalist);
          }
          if (e.type.startsWith('safetymonitor')) {
            e.datalist.forEach((ele) => {
              if (ele.strinstallpos.includes('风门')) {
                obj.gate.datalist.push(ele);
              } else if (ele.strinstallpos.includes('风窗')) {
                obj.window.datalist.push(ele);
              } else if (ele.strinstallpos.includes('工作面')) {
                obj.work_surface.datalist.push(ele);
              } else {
                obj.others.datalist.push(ele);
              }
            });
          }
        }

        return obj;
      },
      {
        /** 用于归类fanlocal */
        fanlocal: { datalist: [] },
        /** 用于归类gate */
        gate: { datalist: [] },
        /** 用于归类window */
        window: { datalist: [] },
        /** 用于归类work_surface */
        work_surface: { datalist: [] },
        others: { datalist: [] },
      }
    );

    return result;
  }

  const { avePressSetting, avePressLinkage, formData, getAvePress, changePassword, linkageControl, settingControl } = usePressControl();

  const modalVisible = ref(false);

  const { configs, fetchConfigs } = useInitConfigs();

  const [updatePwdRegister, { openModal, closeModal, setModalProps }] = useModal();

  function handleChangePassword(values) {
    setModalProps({ confirmLoading: true });
    changePassword(values).finally(() => {
      setModalProps({ confirmLoading: false });
      closeModal();
    });
  }

  function changeIsAuto({ target }) {
    formData.value.isAuto = target.value;
    modalVisible.value = true;
    resolver = (password) => {
      linkageControl(
        { password },
        {
          isAuto: formData.value.isAuto,
        }
      ).finally(() => {
        modalVisible.value = false;
      });
    };
  }
  function changeIsAutoControl({ target }) {
    formData.value.isAutoControl = target.value;
    modalVisible.value = true;
    resolver = (password) => {
      settingControl(
        { password },
        {
          isAutoControl: formData.value.isAutoControl,
        }
      ).finally(() => {
        modalVisible.value = false;
      });
    };
  }

  // function submitLinkageForm(password) {}
  function submitSettingForm() {
    modalVisible.value = true;
    resolver = (password) => {
      settingControl({ password }, avePressSetting.value).finally(() => {
        modalVisible.value = false;
      });
    };
  }

  let resolver: any = null;
  function handleResolve(password) {
    if (resolver) resolver(password);
    resolver = null;
  }

  // 初始化 WebSocket
  function initWebSocket() {
    const token = getToken();
    const userStore = useUserStore();
    const glob = useGlobSetting();
    // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
    const url = `${glob.wsUrl?.replace('https://', 'wss://').replace('http://', 'ws://')}/websocket/${userStore.getUserInfo.id}?token=${token}`;
    connectWebSocket(url);
    onWebSocket((data: any) => {
      console.error('NO ERROR HERE! ', data);
      notification.open({
        message: data.title,
        description: JSON.parse(data.content).info,
        placement: 'topRight',
      });
    });
  }

  const settingFormDisabled = ref(true);
  function editSettingForm() {
    settingFormDisabled.value = !settingFormDisabled.value;
    /**  如果取消了编辑模式，那么需要重置表单 */
    if (settingFormDisabled.value) {
      getAvePress();
    }
  }

  onMounted(() => {
    initWebSocket();
    // getMonitor()
    fetchConfigs('balancePressHome');
    getAvePress();
    loading.value = true;
    mountedThree().then(async () => {
      await setModelType('balancePressBase'); //balancePressBase
      loading.value = false;
      timer = null;
      await getMonitor(true);
      play('startSmoke', 'top', 30, 'open', 0);
    });
    // loading.value = false;
    // timer = null;
    // getMonitor(true);
  });

  onUnmounted(() => {
    destroy();
    if (timer) {
      clearTimeout(timer);
    }
  });
</script>
<style lang="less" scoped>
  @import '/@/design/vent/modal.less';
  @import '../../comment/less/workFace.less';
  @ventSpace: zxm;
  .monitor-container {
    margin-top: 60px;
  }
</style>
