<template>
  <a-spin :spinning="isLoading">
    <!-- 照明区域 -->
    <div>
      <div class="light-area">
        <div class="light-area-tab"></div>
        <span class="light-area-text"> 照明区域 </span>
        <button class="plan" :class="{ enabled: isPlanEnabled, disabled: !isPlanEnabled }" @click="togglePlan">
          {{ isPlanEnabled ? '计划启用' : '计划禁用' }}
        </button>
      </div>
      <!-- 照明区域按钮部分 -->
      <div class="area">
        <template v-if="!showAllButtonsArea">
          <button v-for="(button, index) in limitedButtons1" :key="index"
            :class="{ btn: true, selected: button.selected }" @click="selectButton(button)">
            {{ button.name }}
          </button>
          <div style="margin-top: 10px">
            <span @click="showAllButtonsArea = true" class="openzm"><down-outlined /> 展开</span>
          </div>
        </template>
        <template v-else>
          <button v-for="(button, index) in props.treeData" :key="index" :class="{ btn: true, selected: button.selected }"
            @click="selectButton(button)">
            {{ button.name }}
          </button>
          <div style="margin-top: 10px">
            <span @click="showAllButtonsArea = false" class="openzm"><up-outlined /> 回缩</span>
          </div>
        </template>
      </div>
    </div>
    <!-- 照明回路部分 -->
    <div>
      <div class="circuit-area">
        <div class="circuit-tab"></div>
        <span class="circuit-text">照明回路</span>
        <div class="btn2">
          <button class="openPlan" :class="{ enabled2: isPlanEnabled2, disabled2: !isPlanEnabled2 }" @click="togglePlan2">
            {{ isPlanEnabled2 ? '启用面板' : '禁用面板' }}
          </button>
          <a-switch v-model:checked="selectAllCheckbox" :disabled="singleSelection" :class="{
          'blue-background': selectAllCheckbox,
          'grey-background': !selectAllCheckbox,
        }" @change="toggleAllSelection" />
          <button class="allBtn">全选</button>
          <button class="both" @click="selectAll">
            {{ singleSelection ? '多选' : '单选' }}
          </button>
        </div>
      </div>
      <div class="btnArea">
        <template v-if="!showAllButtons">
          <button v-for="(button, index) in limitedButtons2" :key="index"
            :class="{ btn: true, selected: button.selected }" class="zmhlbtn" @click="toggleSelection(button)">
            <stop-outlined v-if="button.ctrlStatus" />
            {{ button.name }}
          </button>
          <div style="margin-top: 10px">
            <span @click="showAllButtons = true" class="openzm"><down-outlined /> 展开</span>
          </div>
        </template>
        <template v-else>
          <button v-for="(button, index) in buttons2" :key="index" 
          :class="{ btn: true, selected: button.selected }" class="zmhlbtn" @click="toggleSelection(button)">
            <stop-outlined v-if="button.ctrlStatus" />
            {{ button.name }}
          </button>
          <div style="margin-top: 10px">
            <span @click="showAllButtons = false" class="openzm"><up-outlined /> 回缩</span>
          </div>
        </template>
      </div>
    </div>
    <!-- 控制模式部分 -->
    <div>
      <div class="control-area" v-show="showControlMode">
        <div class="control-tab"></div>
        <span class="control-text"> 控制模式 </span>
      </div>
      <!-- 控制模式按钮部分 -->
      <div class="control-mode-btn-area" v-show="showControlMode">
        <button v-for="(button3, index) in controlType" :key="index"
          :class="{ btn: true, selected: button3.type == thisButton.type }" @click="selectButton3(button3)">
          {{ button3.name }}
        </button>
      </div>
    </div>
    <!-- 控制场景部分 -->
    <div>
      <div class="control-scene-area" v-show="showControlScene">
        <div class="control-scene-tab"></div>
        <span class="control-scene-text"> 控制场景 </span>
      </div>
      <!-- 控制场景按钮部分 -->
      <div class="control-scene-btn-area" v-show="showControlScene">
        <button v-for="(button4, index) in controlSceneButtons" :key="index"
          :class="{ btn: true, selected: button4.label === selectedButton4 }" @click="selectButton4(button4)">
          {{ button4.label }}
        </button>
      </div>
    </div>
    <!-- 灯具参数部分（表格） -->
    <div>
      <div class="light-parameters-area" v-if="selectedButton4">
        <div class="light-parameters-tab"></div>
        <span class="light-parameters-text"> 灯具参数 </span>
      </div>
      <div class="light-parameters-textarea" v-if="selectedButton4">
        <table class="custom-table table1">
          <thead>
            <tr :style="{ background: 'rgba(35,45,69)' }">
              <th>开启数量</th>
              <th>亮度(lux)</th>
              <th>色温</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in lightSource" :key="index" @click="handleRowClick(row.num)"
              :style="{ height: '50px' }">
              <td>{{ row.num }}</td>
              <td>{{ row.light }}</td>
              <td>{{ row.temperature }}</td>
            </tr>
          </tbody>
        </table>
        <div style="margin-bottom: 60px;"></div>
      </div>
    </div>
    <!-- 底部按钮区 -->
    <div class="bottom">
        <a-popconfirm
        title="刷新将会取消已作出的修改"
        ok-text="确定"
        cancel-text="取消"
        @confirm="changeConfirm"
        @cancel="changeCancel"
      >
        <button class="flushed">刷新</button>
      </a-popconfirm>
      <button class="execute" @click="showModal">执行</button>
    </div>

    <!-- 点击执行时的弹出框 -->
    <div class="out-dialog" v-if="executeVisible">
      <div class="content" v-if="executeVisible">
        <div>
          <div class="div-operation"></div>
          <span class="text-operation">变更内容 </span>
        </div>
        <div class="j-box" v-for="item in cxList" :key="item.id">
          <div class="journal" style="margin-top: 20px">
            <div class="imgText">
              <div class="zjzm">
                <img class="title-img" src="/asset/image//bulbLogo/21961.png" alt="" />&nbsp;
                <span class="title-text" style="font-size: 20px; font-weight: 500; color: rgba(255, 255, 255, 1)">{{ item.name }}</span>
              </div>
              <button class="cxbtn" @click="delBtn(item.id)">撤销</button>
            </div>
            <div class="btn-box">
              <div class="btn-item">
                <div class="left">控制模式</div>
                <div class="right">
                  <span>手动</span>
                  <img src="/asset/image/bulbLogo/22406.png" alt="" />
                  <span>自动</span>
                </div>
              </div>
              <div class="btn-item">
                <div class="left">
                  亮度
                </div>
                <div class="right">
                  <span>100lux</span>
                  <img src="/asset/image/bulbLogo/22406.png" alt="" />
                  <span>30lux</span>
                </div>
              </div>
              <div class="btn-item">
                <div class="left">
                  控制场景
                </div>
                <div class="right">
                  <span>手动</span>
                  <img src="/asset/image/bulbLogo/22406.png" alt="" />
                  <span>自动</span>
                </div>
              </div>
              <div class="btn-item">
                <div class="left">
                  色温
                </div>
                <div class="right">
                  <span>4000k</span>
                  <img src="/asset/image/bulbLogo/22406.png" alt="" />
                  <span>3800k</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div style="width: 100%; height: 60px;"></div>
      <div class="button-box">
        <button class="cancel" @click="executeVisible = false">取消</button>
        <button class="execute">执行</button>
      </div>
    </div>
  </a-spin>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { controlType } from './treeData'
import {
  DownOutlined,
  UpOutlined,
  StopOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
// 请求
import { http } from '/nerv-lib/util/http';
import { lightingManage } from '/@/api/IlluminationInfo';

// 初始化  =========================================================================

onMounted(() => {
  setArea()
})
// 父组件点击俯视图切换分区时，子组件切换线路
const setArea = () => {
  const data = props.treeData.find(item => {
    return item.id == props.nowArea
  })
  // 默认选中第一个分区
  data.selected = true
  // 修改当前选中的分区
  selectedButton.value = props.nowArea
  // 设置当前显示的回路
  buttons2.value = data.childList
}

// 与父组件的交互  ===================================================================

const props = defineProps({
  // 分区结构（照明区域 > 照明回路）
  treeData: {
    type: Array,
    default: []
  },
  // 父组件选中的分区ID
  nowArea: {
    type: String,
  }
});
// 向上传递修改选择样式
/** 
 * @method changeArea 用于控制俯视图的选中状态
 * @method reset 用于重置按钮区
 */
const emit = defineEmits(['changeArea','reset']);
// 监听父组件选中的分区，并实时修改分区
watch(() => props.nowArea, () => {
  setArea()
  // 分区产生了切换， 线路的选中状态置空
  handleButton.value = ''
})

// 照明区域业务 =======================================================================

// 计划启用状态
const isPlanEnabled = ref(false);
// 计划启用切换事件
const togglePlan = () => {
  isPlanEnabled.value = !isPlanEnabled.value;
};

// 按钮区展开与收起状态
const showAllButtonsArea = ref(false);
// 被选中的分区  默认为1
const selectedButton = ref('1');
// 区域切换（按钮点击-单选）事件
const selectButton = (button: any) => {
  console.log(button,'button')
  // 当前选中按钮
  selectedButton.value = button.id;
  initMenu(1)
  button.selected = true
  buttons2.value = button.childList
  emit('changeArea', button.id);
  handleButton.value = ''
};
// 默认最多展示8个按钮
const limitedButtons1 = computed(() => props.treeData.slice(0, 8));

// 照明回路业务 ======================================================================

// 最近交互过的按钮id，用于禁用和启用
const handleButton = ref('');

// 面板启用/禁用状态
const isPlanEnabled2 = ref(true);
// 面板启用/禁用切换事件
const togglePlan2 = () => {
  // 如果未交互任何按钮
  if (handleButton.value == '') {
    return message.info('请选择照明回路');
  }
  // 获取最近交互过的按钮
  const btn = buttons2.value.find((button) => button.id === handleButton.value)
  let panel = +(!btn.ctrlStatus)
  isLoading.value = true
  http.get(lightingManage.setDisable, { deviceGroup: btn.code, panel }).then(res => {
    if (res.msg === 'success') {
      isPlanEnabled2.value = !isPlanEnabled2.value;
      btn.ctrlStatus = panel
      isLoading.value = false
    } else {
      isLoading.value = false
    }
  }).catch(() => { isLoading.value = false })
};

// 是否单选，状态
let singleSelection = ref(true);
// 多选与单选切换事件
const selectAll = () => {
  selectAllCheckbox.value = false
  buttons2.value.forEach((button) => {
    button.selected = false;
  });
  singleSelection.value = !singleSelection.value;
  // 线路按钮被重置，
  showControlMode.value = false
  emit('changeArea', [selectedButton.value])
};

// 全选状态
const selectAllCheckbox = ref(false);
// 全选切换事件（switch）
const toggleAllSelection = () => {
  let arr = [selectedButton.value]
  // 全选
  if (selectAllCheckbox.value) {
    buttons2.value.forEach((item) => {
      item.selected = true;
      arr.push(item.id)
    });
    // 全不选
  } else {
    buttons2.value.forEach((item) => {
      item.selected = false;
    });
    showControlMode.value = false
  }
  emit('changeArea', arr)
};

// 照明回路的按钮切换
const toggleSelection = (button: any) => {
  // 存储一次按钮ID，用于禁用/启用交互
  handleButton.value = button.id
  // 根据按钮状态，展示禁用/启用按钮文本
  if (button.ctrlStatus) {
    isPlanEnabled2.value = true
  } else {
    isPlanEnabled2.value = false
  }

  // 选择时反控俯视图
  let level1 = selectedButton.value
  let level2 = button.id
  // 单选模式，需将所有按钮设为false
  if (singleSelection.value) {
    buttons2.value.forEach(item => {
      item.selected = false;
    });
    emit('changeArea', [level1, level2])
    button.selected = !button.selected;
  } else {
    // 多选模式传值
    button.selected = !button.selected;
    const arr = [level1]
    buttons2.value.forEach(item => {
      if (item.selected) {
        arr.push(item.id)
      }
    });
    emit('changeArea', arr)
  }
  // 用于展示控制模式
  if (button.selected) {
    // 发生了选中事件
    showControlMode.value = true
    thisButton.value = button
    if (button.type == 3) {
      showControlScene.value = true
    } else {
      showControlScene.value = false
    }
  } else {
    // 未发生选中 或 多选被取消
    showControlMode.value = false
    thisButton.value = { type: '0' }
  }
};

// 照明回路所有按钮
const buttons2 = ref([]);
// 按钮区展开与收起状态
const showAllButtons = ref(false);
// 默认最多展示8个按钮
const limitedButtons2 = computed(() => buttons2.value.slice(0, 8));

// 控制模式业务 ====================================================================

// 决定该区域是否显示
const showControlMode = ref(false);
const thisButton = ref({ type: 0 })
// 控制模式 - 按钮切换
const selectButton3 = (button3) => {
  thisButton.value.type = button3.type
  showControlScene.value = button3.name === '手动';
  selectedButton4.value = null; // 清空选中的控制场景按钮
};

// 控制场景业务 =====================================================================

// 决定该区域是否显示
const showControlScene = ref(false);
// 控制场景 - 所有按钮
const controlSceneButtons = ref([
  { label: '检修', selected: false },
  { label: '午休', selected: false },
  { label: '疏散', selected: false },
  { label: '客流高峰', selected: false },
]);
// 控制场景 - 当前选择按钮
const selectedButton4 = ref(null);
// 控制场景 - 按钮切换
const selectButton4 = (button4) => {
  selectedButton4.value = button4.label;
};

// 灯具参数表格 =====================================================================

// 灯具参数 - 表格数据
const lightSource = ref([{ num: '8/10', light: '100', temperature: '4200' }]);

let trIndex = ref('-1');
const handleRowClick = (index: any) => {
  trIndex.value = index;
  if (index === trIndex.value) {
    console.log('tri');
  }
};

// 内侧弹窗 ========================================================================

const cxList = ref([
  {
    id: '1',
    name: '站厅照明  1区',
    manual: '手动',
    automatic: '自动',
    brightness: '100lux',
    brightness2: '30lux',
    manual2: '手动',
    automatic2: '自动',
    brightness3: '4000k',
    brightness4: '3800k',
  },
  {
    id: '2',
    name: '站厅照明  2区',
    manual: '手动',
    automatic: '自动',
    brightness: '100lux',
    brightness2: '30lux',
    manual2: '手动',
    automatic2: '自动',
    brightness3: '4000k',
    brightness4: '3800k',
  },
  {
    id: '3',
    name: '站厅照明  3区',
    manual: '手动',
    automatic: '自动',
    brightness: '100lux',
    brightness2: '30lux',
    manual2: '手动',
    automatic2: '自动',
    brightness3: '4000k',
    brightness4: '3800k',
  },
]);
//撤销
const delBtn = (id: any) => {
  cxList.value.pop(id);
  console.log(cxList.value.length);

  if (cxList.value.length === 0) {
    executeVisible.value = false;
  }
};

// 其他业务 ========================================================================

const isLoading = ref(false)

// 用于初始化5级联动的菜单
const initMenu = (tier: number) => {
  // 1 = 照明区域 - 切换时，重置以下所有菜单
  if (tier == 1) {
    // 切换前，清除照明回路的选中状态
    // buttons2.value.forEach(item => {
    //   item.selected = false
    // })
    // // 切换后，清空所有选中状态
    // props.treeData.forEach(item => {
    //   item.selected = false
    // })
    emit('reset')
    // 控制模式 隐藏
    showControlMode.value = false;
    // 控制场景 隐藏
    showControlScene.value = false;
    // 灯具参数 隐藏
    selectedButton4.value = null;
  } else if (tier == 2) {
    // 控制场景 隐藏
    showControlScene.value = false;
    // 灯具参数 隐藏
    selectedButton4.value = null;
  }
}
// 刷新
const refresh = () => {
  // 关闭执行弹窗
  executeVisible.value = false
  // 设置当前选中的序列
  selectedButton.value = '1';
  emit('changeArea', ['1']);
  emit('reset')
  let data = props.treeData[0]
  // 默认选中
  data.selected = true
  buttons2.value = data.childList

  showControlMode.value = false;
  showControlScene.value = false;
  selectedButton4.value = null;
};
// 执行确认
const executeVisible = ref<boolean>(false);
const showModal = () => {
  executeVisible.value = true;
};

// 确定
const changeConfirm = () => {
  refresh()
}

// 取消
const changeCancel = () => {

}

</script>
<style lang="less" scoped>
@import "./dialogStyle.less";
@import "./tabs1.less";
</style>
