<template>
  <div style="width: 100%; height: 100%">
    <div style="display: flex">
      <a-tabs
        v-model:activeKey="activeKey"
        style="
          height: 5%;
          width: 98.5%;
          margin-top: 0.5%;
          padding-left: 1.5%;
          background: #ffffff;
          font-family: 'PingFang SC';
          font-size: 16px;
          font-weight: 700;
          letter-spacing: 1.33px;
          line-height: 21px;
        ">
        <a-tab-pane key="1" tab="综合数据" />
        <a-tab-pane key="2" tab="历史数据" />
        <a-tab-pane key="3" tab="平均数据" />
      </a-tabs>
      <a-button
        type="primary"
        style="position: absolute; margin-right: 30px; margin-top: 10px; right: 30px"
        @click="configurePoint"
        v-if="activeKey == '1'">
        配置监测点位
      </a-button>
    </div>

    <aggregate-data ref="aggregateDataRef" v-if="activeKey == '1'" style="height: 85%" />
    <history-data ref="historyDataRef" v-if="activeKey == '2'" />
    <average-data ref="averageDataRef" v-if="activeKey == '3'" />
  </div>

  <a-modal
    :visible="openModal"
    title="配置监测点位"
    style="width: 65%"
    @ok="handleOk"
    @cancel="closeOpenUpload">
    <div style="display: flex">
      <div style="width: 15%; height: 100%; position: sticky; top: 0; align-self: flex-start">
        <a-tabs
          v-model:activeKey="typeValue"
          tab-position="left"
          @tabScroll="callback"
          @change="queryDeviceArea">
          <a-tab-pane v-for="item in typeList" :key="item.value" :tab="item.label" />
        </a-tabs>
      </div>
      <div style="width: 85%; height: 100%">
        <a-table
          :columns="tableColumns"
          :data-source="data"
          bordered
          :pagination="false"
          rowKey="deviceInfoCode"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
          <template #bodyCell="{ text, column, record }">
            <template v-if="column.dataIndex === 'useFlag'">
              <a-switch
                :checked="text"
                :checked-value="1"
                :unCheckedValue="0"
                @change="(checked) => updateShowed(record)" />
            </template>
            <template
              v-if="column.dataIndex === 'device1Area' || column.dataIndex === 'device2Area'">
              <a-tooltip v-if="text.length > 15" :title="text">
                {{ text.slice(0, 15) }}...
              </a-tooltip>
              <span v-else>{{ text }}</span>
            </template>
          </template>
          <template #title>
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
                width: 100%;
              ">
              <div style="display: flex; align-items: center; width: 85%">
                <div style="width: 10%">数据列表</div>
                <a-cascader
                  :options="treeData2"
                  v-model:value="quyuvalue"
                  placeholder="请选择所属区域"
                  :field-names="{
                    children: 'childList',
                    label: 'name',
                    value: 'id',
                  }"
                  multiple
                  max-tag-count="responsive" />
                <a-select
                  v-model:value="useFlag"
                  placeholder="请选择监测状态"
                  style="width: 20%; margin-left: 1%"
                  :options="useFlagList" />
                <a-input
                  v-model:value="areaName"
                  placeholder="请输入设备名称"
                  style="width: 20%; margin-left: 1%" />
                <a-button style="margin-left: 10px" @click="resetting"> 重置 </a-button>
                <a-button type="primary" style="margin-left: 10px" @click="queryDeviceInfoListPage">
                  搜索
                </a-button>
              </div>
            </div>
            <div>
              <a-divider />
              <a-button
                type="primary"
                size="small"
                @click="startOrEnd(true)"
                :disabled="selectedRowKeys.length == 0">
                批量开启
              </a-button>
              <a-button
                type="primary"
                size="small"
                style="margin-left: 10px"
                @click="startOrEnd(false)"
                :disabled="selectedRowKeys.length == 0">
                批量关闭
              </a-button>
            </div>
          </template>
        </a-table>
        <a-pagination
          :current="queryParams.pageNum"
          :total="total"
          :page-size="queryParams.pageSize"
          style="display: flex; justify-content: center; margin-top: 16px"
          :show-size-changer="true"
          :show-quick-jumper="true"
          @change="onChange" />
      </div>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue';
  import aggregateData from './aggregateData/index.vue';
  import historyData from './historyData/index.vue';
  import averageData from './averageData/index.vue';
  import { Pagination, TabsProps, TableColumnType, TreeSelectProps } from 'ant-design-vue';
  import { environmentMonitor } from '/@/api/monitor';
  import { http } from '/nerv-lib/util';
  import { dict, getEnum } from '/@/api';

  const total = ref<number>();
  const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
  });
  const aggregateDataRef = ref();
  const historyDataRef = ref();
  const averageDataRef = ref();

  var activeKey = ref('1');
  var typeValue = ref();
  const openModal = ref<boolean>(false);

  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;

  defineOptions({
    name: 'EnvironmentMonitorIndex', // 与页面路由name一致缓存才可生效
    components: {
      'a-pagination': Pagination,
    },
  });

  const typeList = ref();

  const quyuvalue = ref<string[]>([]);
  const useFlag = ref<Number | null>();
  const useFlagList = ref();
  useFlagList.value = [
    {
      value: 0,
      label: '关闭',
    },
    {
      value: 1,
      label: '开启',
    },
  ];
  const areaName = ref<string>();
  let tableColumns = ref<TableColumnType[]>([]);
  const treeData2 = ref<TreeSelectProps['treeData']>([]);
  const data = ref();

  const selectedRowKeys = ref([]);
  const onSelectChange = (selectedRowKey: string | number[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKey);
    selectedRowKeys.value = selectedRowKey;
  };
  // 分页器
  const onChange = (pageNumber: number, size: number) => {
    queryParams.value.pageNum = pageNumber;
    queryParams.value.pageSize = size;

    // getTableList();
  };
  const configurePoint = () => {
    openModal.value = true;
  };
  // 上传凭证弹窗点击确定
  const handleOk = (e: MouseEvent) => {
    console.log(e);
    openModal.value = false;
  };
  // 关闭上传凭证弹窗
  const closeOpenUpload = () => {
    openModal.value = false;
  };
  const callback: TabsProps['onTabScroll'] = (val) => {
    console.log(val);
  };
  // 重置
  const resetting = () => {
    quyuvalue.value = [];
    useFlag.value = null;
    areaName.value = '';
  };
  // 修改是否显示状态
  const updateShowed = (record: any) => {
    let url = '';
    if (record.useFlag == 0) {
      record.useFlag = 1;
      url = environmentMonitor.startUpDevice;
    } else {
      record.useFlag = 0;
      url = environmentMonitor.stopDevice;
    }
    let params = [
      {
        orgId: orgId.value,
        code: typeValue.value, // 点位flag
        deviceInfoCode: record.deviceInfoCode,
      },
    ];
    http.post(url, params).then((res) => {
      console.log('🚀 ~ http.post ~ res:', res);
    });
  };
  // 批量修改是否显示状态
  const startOrEnd = (flag: Boolean) => {
    let url = '';
    if (flag) {
      url = environmentMonitor.startUpDevice;
    } else {
      url = environmentMonitor.stopDevice;
    }
    let params = [];

    for (let i = 0; i < selectedRowKeys.value.length; i++) {
      params.push({
        orgId: orgId.value,
        code: typeValue.value, // 点位flag
        deviceInfoCode: selectedRowKeys.value[i],
      });
    }
    // let params = [
    //   {
    //     orgId: orgId.value,
    //     code: typeValue.value, // 点位flag
    //     deviceInfoCode: record.deviceInfoCode,
    //   },
    // ];
    http.post(url, params).then((res) => {
      selectedRowKeys.value = [];
      queryDeviceInfoListPage();
    });
  };
  const queryDeviceInfoListPage = () => {
    http
      .post(environmentMonitor.queryDeviceInfoListPage, {
        orgId: orgId.value,
        pointCode: typeValue.value, //点位flag
        pageNum: queryParams.value.pageNum,
        pageSize: queryParams.value.pageSize,
        deviceName: areaName.value, //设备名搜索
        useFlag: useFlag.value, // 是否弃用搜索
        area2: quyuvalue.value, // 地区名数组查
      })
      .then((res) => {
        total.value = res.data.total;
        data.value = res.data.records;
      });
  };
  // 获取区域数据
  const queryDeviceArea = () => {
    http
      .get(environmentMonitor.queryDeviceArea, { orgId: orgId.value, point: typeValue.value })
      .then((res) => {
        treeData2.value = res.data;
        // if (treeData2.value && treeData2.value.length > 0) {
        //   quyuvalue.value = [treeData2.value[0].childList[0].id];
        // }
      });

    queryDeviceInfoListPage();
  };
  onMounted(async () => {
    // 获取环境参数
    let typeData = await getEnum({ params: { enumType: 'EnvironmentTypeEnum' } });
    typeData.data.forEach((item: any) => {
      item.code = item.value;
      item.value = item.flag;
    });
    typeList.value = typeData.data;
    if (typeList.value && typeList.value.length > 0) {
      typeValue.value = typeList.value[0].value;
      await queryDeviceArea();
    }

    // 获取区域数据

    // 获取左侧选项
    // typeList.value = [
    //   {
    //     id: 1,
    //     value: '温度',
    //   },
    //   {
    //     id: 2,
    //     value: 'CO2浓度',
    //   },
    //   {
    //     id: 3,
    //     value: 'PM2.5',
    //   },
    //   {
    //     id: 4,
    //     value: '光照度',
    //   },
    //   {
    //     id: 5,
    //     value: 'TVOC',
    //   },
    //   {
    //     id: 6,
    //     value: '湿度',
    //   },
    // ];
    // 默认选中第一个
    // pointKey.value = typeList.value[0].id;
    // 表头
    tableColumns.value = [
      {
        title: '序号',
        customRender: (text: any) => {
          return text.index + 1;
        },
      },
      {
        title: '设备名称',
        dataIndex: 'deviceName',
      },
      {
        title: '设备型号',
        dataIndex: 'deviceRatepay',
      },
      {
        title: '设备一级区域',
        dataIndex: 'device1Area',
        // width: 300,
        // ellipsis: true,
        // textNumber: 15,
        // textEllipsis: true,
        // ellipsis: {
        //   showTitle: false, // 设置为 false 在悬浮时显示 tooltip
        // },
      },
      {
        title: '设备二级区域',
        dataIndex: 'device2Area',
      },
      {
        title: '设备详细位置',
        dataIndex: 'deviceAddress',
      },
      {
        title: '是否纳入计算',
        dataIndex: 'useFlag',
      },
    ];
    // 获取区域数据
    // treeData2.value = [
    //   {
    //     label: '办公区',
    //     value: '0-0',
    //     children: [
    //       {
    //         label: '办公一区',
    //         value: '0-0-0',
    //       },
    //       {
    //         label: '办公二区',
    //         value: '0-0-1',
    //       },
    //       {
    //         label: '办公三区',
    //         value: '0-0-2',
    //       },
    //       {
    //         label: '办公四区',
    //         value: '0-0-3',
    //       },
    //     ],
    //   },
    //   {
    //     label: '站厅',
    //     value: '0-1',

    //     children: [
    //       {
    //         label: '站厅一区',
    //         value: '0-1-0',
    //         // disabled: true,
    //       },
    //       {
    //         label: '站厅二区',
    //         value: '0-1-1',
    //       },
    //       {
    //         label: '站厅三区',
    //         value: '0-1-2',
    //       },
    //       {
    //         label: '站厅四区',
    //         value: '0-1-3',
    //       },
    //     ],
    //   },
    // ];
    // 获取表格数据
    // data.value = [
    //   { areaName: '设备', showed: '1' },
    //   { areaName: '设备', showed: '1' },
    // ];
    queryDeviceInfoListPage();
  });
</script>
<style lang="less" scoped>
  ::v-deep .ant-tabs-tab {
    font-weight: 700; /* 选中标签的加粗 */
    // font-size: 16px;
    // letter-spacing: 1.33px;
    color: #666666 !important;
  }
  ::v-deep .ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn {
    // background-color: #f0f0f0; /* 自定义选中背景色 */
    // color: #1890ff; /* 自定义选中文字颜色 */
    // border-radius: 5px; /* 选中标签的圆角 */
    // font-weight: bold; /* 选中标签的加粗 */

    color: #000000 !important;
  }

  ::v-deep .ant-tabs-tab:hover {
    color: #000000; /* 悬停时的文字颜色 */
  }
</style>
