<template>
  <div class="internet-detail-container" v-loading="loading">
    <div class="gauge-charts-container">
      <div class="gauge-charts-wrapper">
        <div class="gauge-charts-wrapper-li" v-for="(item, i) in getGaugeData">
          <div class="gauge-card" v-for="(listItem, j) in item.list">
            <GaugeChart
              height="250px"
              :value="listItem.value"
              :min="listItem.min"
              :max="listItem.max"
              :title="listItem.name"
              :unit="listItem.unit"
              :colors="['#5470C6', '#91CC75', '#FAC858', '#EE6666']"
              :options="{ pointer: { itemStyle: { color: '#5470C6' } } }"
              :ref="'gaugeChartRef'"
            />
          </div>
        </div>
      </div>

      <div class="status-wrapper">
        <el-form label-width="150px" style="width: 100%">
          <el-row>
            <template v-for="obj in realData">
              <!-- 过滤掉运行状态  v-if="!['status', 'status_m'].includes(key)" -->
              <el-col :span="12">
                <el-form-item
                  v-if="
                    obj?.dataType?.type == 'enum' || obj?.dataType?.type == 'bool'
                  "
                  :label="obj.name + ':'"
                >
                  <span>{{ obj.specs[obj.value] }}</span>
                </el-form-item>
                <el-form-item v-else :label="obj.name + ':'">
                  <span>{{ obj.value }}</span>
                  <span style="margin-left: 5px" v-if="obj.unit">{{
                    obj.unit
                  }}</span>
                </el-form-item>
              </el-col>
            </template>
            <!-- 运行状态设置 -->
            <el-col :span="12" v-if="realData.status_m">
              <el-form-item label="运行状态">
                <div class="yx-warp">
                  <span>{{ realData.status_m.value }}</span>
                  <span class="sz-span" @click="handlsz">设置</span>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>

    <!-- 折线图区域 -->
    <div class="line-charts-wrapper">
      <div class="chart-card" v-for="item in historyData">
        <el-row :gutter="20">
          <el-col :span="8">{{ item.name }}</el-col>
          <el-col :span="8"
            ><span class="detail-span"
              >最高值<span class="detail-value"
                >{{ item.maxValue }} {{ item.unit }}</span
              ></span
            >
            |
            <span class="detail-span"
              >最低值<span class="detail-value"
                >{{ item.minValue }} {{ item.unit }}</span
              ></span
            >
            |
            <span class="detail-span"
              >平均值<span class="detail-value" style="color: rgb(8, 64, 213)"
                >{{ item.avgValue }} {{ item.unit }}</span
              ></span
            ></el-col
          >
          <el-col :span="8">
            <div class="tools">
              <div class="">
                <el-date-picker
                  :clearable="false"
                  v-model="item.chartTime"
                  :type="item.timeType"
                  placeholder="选择日期"
                  :picker-options="pickerOptions"
                >
                </el-date-picker>
              </div>
              <div class="timeType">
                <span
                  :class="{ active: item.timeType === 'date' }"
                  @click="dateClick(item, 'date')"
                  >日</span
                >
                <!-- <span
                        :class="{ active: item.timeType === 'week' }"
                        @click="dateClick(item, 'week')"
                        >周</span
                        > -->
                <span
                  :class="{ active: item.timeType === 'month' }"
                  @click="dateClick(item, 'month')"
                  >月</span
                >
                <span
                  :class="{ active: item.timeType === 'year' }"
                  @click="dateClick(item, 'year')"
                  >年</span
                >
              </div>
              <el-button
                type="primary"
                size="small"
                @click="refreshSingleChart(item)"
                >查询</el-button
              >
            </div>
          </el-col>
        </el-row>
        <LineChart
          :data="item.trendData"
          title=""
          xAxisName="时间"
          :yAxisName="item.unit"
          height="300px"
          :options="{}"
        />
      </div>
    </div>
    <runningDialog
      ref="runningDialog"
      :id="info.id"
      @succeed="getRealData"
    ></runningDialog>
    <ele-modal
      title="点位配置"
      :visible.sync="visible"
      v-if="visible"
      width="750px"
      append-to-body
    >
      <ele-pro-table
        max-height="500px"
        ref="table1"
        :columns="columns"
        :datasource="gaugeDataTable"
        :selection.sync="selection"
        row-key="name"
        :needPage="false"
      >
        <template v-slot:checked="{ row }">
          <el-switch
            v-if="row.max !== undefined && row.min !== undefined"
            :active-value="1"
            :inactive-value="0"
            v-model="row.checked"
          />
        </template>
        <template v-slot:checked1="{ row }">
          <el-switch
            :active-value="1"
            :inactive-value="0"
            v-model="row.checked1"
          />
        </template>
      </ele-pro-table>
      <div slot="footer">
        <el-button type="primary" @click="handelConfirm"> 保存</el-button>
        <el-button @click="visible = false"> 取消</el-button>
      </div>
    </ele-modal>
  </div>
</template>

<script>
  import GaugeChart from './GaugeChart.vue';
  import LineChart from './LineChart.vue';
  import {
    getRealData,
    getHistoryData,
    updateIotDashboardPosition
  } from '@/api/ledgerAssets/equipment.js';
  import { getMonday } from '@/utils/index';
  import runningDialog from './runningDialog.vue';

  export default {
    props: {
      info: {
        type: Object,
        default: () => ({})
      },
      iotDashboardPoint: {
        type: Object,
        default: () => ({})
      },
      id: {
        type: String,
        default: ''
      }
    },
    name: 'InternetDetail',
    components: {
      GaugeChart,
      LineChart,
      runningDialog
    },
    data() {
      return {
        loading: false,
        visible: false,
        realData: [],
        dict: {
          chartTime: {
            date: 3,
            month: 2,
            year: 1
          }
        },
        columns: [
          // {
          //   width: 80,
          //   type: 'selection',
          //   label: '是否显示',
          //   columnKey: 'selection',
          //   align: 'center'
          // },
          {
            columnKey: 'index',
            type: 'index',
            label: '序号',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            label: '是否显示到仪表盘',
            slot: 'checked',
            width: 180,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            label: '是否显示到卡片',
            slot: 'checked1',
            width: 180,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'name',
            label: '名称',
            showOverflowTooltip: true
          }
        ],
        gaugeData: [],
        selection: [],
        historyData: [], // 存储历史数据数组
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        }
      };
    },
    computed: {
      getGaugeData() {
        let list = [];
        let gaugeData = this.iotDashboardPoint.length
          ? this.gaugeData.filter((item) =>
              this.iotDashboardPoint.find(
                (Point) => Point.identifier == item.identifier&&Point.checked
              )
            )
          : this.gaugeData.filter((item, index) => index < 6);

        const perRow = gaugeData.length < 5 ? 2 : 3;

        for (let i = 0; i < gaugeData.length; i += perRow) {
          list.push({
            list: gaugeData.slice(i, i + perRow)
          });
        }
        this.$nextTick(() => {
          gaugeData.forEach((item, index) => {
            if (this.$refs.gaugeChartRef[index]) {
              this.$refs.gaugeChartRef[index].handleResize();
            }
          });
        });
        return list;
      }
    },

    watch: {
      // 监听info属性变化，当info数据加载完成后执行getRealData
      info: {
        handler(newInfo) {
          if (newInfo && Object.keys(newInfo).length > 0) {
            this.getRealData();
          }
        },
        deep: true,
        immediate: true
      }
    },

    mounted() {
      // 只有当info已有数据时才初始化
      // if (this.info && Object.keys(this.info).length > 0) {
      //   this.getRealData();
      // }
    },

    beforeDestroy() {
      // 组件销毁前的清理工作
    },
    methods: {
      handlsz() {
        this.$refs.runningDialog.open();
      },
      // 刷新单个图表数据
      async refreshSingleChart(item) {
        try {
          const updatedData = await this.getHistoryDatas(item);
          console.log('updatedData~~~', updatedData);
          // 找到对应的图表数据并更新
          const index = this.historyData.findIndex(
            (d) => d.identifier === item.identifier
          );
          if (index !== -1) {
            this.$set(this.historyData, index, updatedData);
          }
          console.log(`刷新了图表 ${item.name || item.identifier} 的数据`);
        } catch (error) {
          console.error(
            `刷新图表 ${item.name || item.identifier} 数据失败:`,
            error
          );
        }
      },

      // 刷新所有历史数据
      async refreshHistoryData() {
        try {
          // 并行请求所有property的历史数据
          const historyPromises = this.gaugeData.map((item) =>
            this.getHistoryDatas(item)
          );

          // 等待所有请求完成并存储结果
          this.historyData = await Promise.all(historyPromises);
          console.log('刷新后的历史数据数组~~~~~', this.historyData);
        } catch (error) {
          console.error('刷新历史数据失败:', error);
        }
      },
      edit() {
        this.gaugeDataTable.forEach((item, index) => {
          let data = this.iotDashboardPoint.find(
            (point) => point.identifier == item.identifier
          );
          if (data) {
            this.$set(this.gaugeDataTable, index, data);
          } else {
            this.$set(this.gaugeDataTable[index], 'checked', 0);
            this.$set(this.gaugeDataTable[index], 'checked1', 0);
          }
        });
        console.log(this.gaugeDataTable, 'this.gaugeDataTable');
        this.visible = true;
      },
      // 请求实时数据
      async getRealData() {
        this.loading = true;
        try {
          // 获取实时数据
          const res = await getRealData(this.id);
          this.realData = res;
          console.log(this.realData, 'this.realData');

          // 处理属性映射
          const tempData = this.info.properties || [];
          this.realData.forEach((item, index) => {
            tempData?.forEach((property) => {
              if (property.identifier == item.identifier) {
                item.max = property.dataType.specs.max;
                item.min = property.dataType.specs.min;
                item.propertyUnit = property.dataType.specs.unit;
                item.unitName = property.dataType.specs.unitName;
                item.specs = property.dataType.specs;
                item.dataType = property.dataType;
                item.propertyName = property.name;
                item.accessMode = property.accessMode;
                item.saveHistory = property.saveHistory;
                item.required = property.required;

                // item.value = property.dataType.specs.scale ? item.value / property.dataType.specs.scale : item.value;
                // 为每个图表添加独立的状态
                item.chartTime = new Date();
                item.timeType = 'month';
              }
            });
          });

          const gaugeData = this.realData.filter(
            (item) => item.max !== undefined && item.min !== undefined
          );
          this.gaugeData = gaugeData;
          this.gaugeDataTable = JSON.parse(JSON.stringify(this.realData));
          // console.log('info~~~~~', this.info);
          console.log('实时数据~~~~~', this.realData);

          // 并行请求所有property的历史数据
          const historyPromises = this.gaugeData.map((item) => {
            if (item.saveHistory) {
              return this.getDefaultHistoryData(item);
            }
            return null;
          });

          // 等待所有请求完成并存储结果
          this.historyData = await Promise.all(historyPromises);

          console.log('历史数据数组~~~~~', this.historyData);
        } catch (error) {
          console.error('获取数据失败:', error);
        } finally {
          this.loading = false;
        }
      },
      // 请求历史数据
      async getDefaultHistoryData(item) {
        try {
          // 确保chartTime和timeType属性存在，提供默认值
          // chartTime 可能是 Date 对象或字符串，统一转换为 Date 对象
          const chartTime = item.chartTime
            ? new Date(item.chartTime)
            : new Date();
          const timeType = item.timeType || 'month';

          // 第一步：先获取时间范围，确保时间参数有效
          let time;
          try {
            // 调用getTimeList方法获取时间范围
            time = this.getTimeList(chartTime, timeType);

            // 验证时间范围的有效性
            if (!time || !time.startTime || !time.endTime) {
              // 提供默认时间范围
              const defaultDate = new Date().toISOString().split('T')[0];
              time = {
                startTime: defaultDate + ' 00:00:00',
                endTime: defaultDate + ' 23:59:59'
              };
            }
          } catch (timeError) {
            // 提供默认时间范围作为最后保障
            const defaultDate = new Date().toISOString().split('T')[0];
            time = {
              startTime: defaultDate + ' 00:00:00',
              endTime: defaultDate + ' 23:59:59'
            };
          }
          const response = {};

          // 设置必要的属性
          response.identifier = item.identifier || '';
          response.name = item.name || '';
          response.unit = item.unit || '';
          response.unitName = item.unitName || '';
          response.chartTime = chartTime;
          response.timeType = timeType;

          // 初始化趋势数据结构
          const trendData = {
            xAxis: [],
            series: [
              {
                name: '',
                data: [],
                color: '#5470C6'
              }
            ]
          };
          response.trendData = trendData;
          response.timeHistoryList = [];

          return response;
        } catch (error) {
          // console.error(`获取属性 ${item.name || item.identifier} 的历史数据失败:`, error);
        }
      },
      handelConfirm() {
        if (this.gaugeDataTable.filter((item) => item.checked).length > 6) {
          return this.$message.warning('仪表盘显示点位不能大于6个！');
        }
        if (this.gaugeDataTable.filter((item) => item.checked1).length > 4) {
          return this.$message.warning('卡片显示点位不能大于4个！');
        }
        updateIotDashboardPosition({
          iotDashboardPoint: this.gaugeDataTable,
          id: this.id
        }).then((res) => {
          this.$emit('success');
          this.visible = false;
        });
      },
      // 请求历史数据
      async getHistoryDatas(item) {
        try {
          // 确保chartTime和timeType属性存在，提供默认值
          const chartTime =
            item.chartTime || new Date().toISOString().split('T')[0];
          const timeType = item.timeType || 'month';

          // 第一步：先获取时间范围，确保时间参数有效
          // console.log(`开始获取时间范围 - 属性: ${item.name || item.identifier}, chartTime: ${chartTime}, timeType: ${timeType}`);

          let time;
          try {
            // 调用getTimeList方法获取时间范围
            time = this.getTimeList(chartTime, timeType);

            // 验证时间范围的有效性
            if (!time || !time.startTime || !time.endTime) {
              // 提供默认时间范围
              const defaultDate = new Date().toISOString().split('T')[0];
              time = {
                startTime: defaultDate + ' 00:00:00',
                endTime: defaultDate + ' 23:59:59'
              };
            }
          } catch (timeError) {
            console.error('获取时间范围时出错:', timeError);
            // 提供默认时间范围作为最后保障
            const defaultDate = new Date().toISOString().split('T')[0];
            time = {
              startTime: defaultDate + ' 00:00:00',
              endTime: defaultDate + ' 23:59:59'
            };
          }

          // 安全获取apiTimeType
          let apiTimeType = 'month'; // 默认值
          try {
            apiTimeType = this.dict?.chartTime?.[timeType] || 'month';
          } catch (e) {
            console.warn('获取API时间类型失败，使用默认值month:', e);
          }

          // 构建完整的请求参数
          const requestParams = {
            startTime: time.startTime,
            endTime: time.endTime,
            property: item.identifier,
            substanceId: this.id,
            timeType: apiTimeType
          };
          // 第三步：发送API请求获取历史数据
          console.log(
            `开始发送API请求 - 属性: ${item.name || item.identifier}, 参数:`,
            requestParams
          );
          const res = await getHistoryData(requestParams);
          console.log(
            `API请求完成 - 属性: ${item.name || item.identifier}, 结果:`,
            res
          );
          // 处理API返回结果，确保res是对象
          const response = res || {};

          // 设置必要的属性
          response.identifier = item.identifier || '';
          response.name = item.name || '';
          response.unit = item.unit || '';
          response.unitName = item.unitName || '';
          response.chartTime = chartTime;
          response.timeType = timeType;

          // 初始化趋势数据结构
          const trendData = {
            xAxis: [],
            series: [
              {
                name: response.name,
                data: [],
                color: '#5470C6'
              }
            ]
          };

          // 处理时间历史数据，确保timeHistoryList是数组
          const timeHistoryList = Array.isArray(response.timeHistoryList)
            ? response.timeHistoryList
            : [];

          timeHistoryList.forEach((i) => {
            if (i && i.time !== undefined && i.value !== undefined) {
              trendData.xAxis.push(i.time);
              trendData.series[0].data.push(i.value);
            }
          });
          response.trendData = trendData;
          response.timeHistoryList = timeHistoryList;
          console.log(
            `获取属性 ${
              item.name || item.identifier
            } 的历史数据成功，数据条数:`,
            timeHistoryList.length
          );

          return response;
        } catch (error) {
          console.error(
            `获取属性 ${item.name || item.identifier} 的历史数据失败:`,
            error
          );
          // 返回一个默认的响应对象，避免 undefined
          return {
            identifier: item.identifier || '',
            name: item.name || '',
            unit: item.unit || '',
            unitName: item.unitName || '',
            chartTime: item.chartTime || new Date(),
            timeType: item.timeType || 'month',
            trendData: {
              xAxis: [],
              series: [{ name: item.name || '', data: [], color: '#5470C6' }]
            },
            timeHistoryList: []
          };
        }
      },
      dateClick(item, dateType) {
        console.log(item, dateType);
        const now = new Date();
        item.chartTime = now;
        item.timeType = dateType;
      },
      // 日期数据格式化
      getTimeList(date, timeType) {
        function fnNum(num) {
          return num < 10 ? '0' + num : num;
        }

        let startTime;
        let endTime;

        let ndate = date ? new Date(date) : new Date();
        let year = ndate.getFullYear();
        let month = ndate.getMonth() + 1;
        let day = ndate.getDate();

        switch (timeType) {
          case 'date': {
            let _date = `${year}-${fnNum(month)}-${fnNum(day)}`;
            startTime = _date + ' 00:00:00';
            endTime = _date + ' 23:59:59';
            break;
          }
          case 'month': {
            let month = getMonday(date);
            startTime = month[0] + ' 00:00:00';
            endTime = month[1] + ' 23:59:59';
            break;
          }
          case 'year': {
            let year = ndate.getFullYear();
            startTime = year + '-01-01 00:00:00';
            endTime = year + '-12-31 23:59:59';
            break;
          }
          default:
            break;
        }
        return {
          startTime,
          endTime
        };
      }
    }
  };
</script>

<style scoped lang="scss">
  .internet-detail-container {
    /* padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px; */
  }

  .gauge-charts-container {
    display: flex;
    gap: 30px;
    //   flex-wrap: wrap;
  }

  .section-title {
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 20px;
  }

  .section-subtitle {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
    margin: 30px 0 20px;
  }

  .gauge-charts-wrapper {
    // display: flex;
    // gap: 10px;
    // flex-wrap: wrap;
    width: 60%;
  }
  .gauge-charts-wrapper-li {
    display: flex;
    gap: 10px;
    // flex-wrap: wrap;
    width: 100%;
  }

  .status-wrapper {
    width: 40%;
  }

  .line-charts-wrapper {
    margin-top: 30px;
  }

  .detail-span {
    margin-right: 10px;
    margin-left: 10px;
  }

  .detail-value {
    font-weight: 600;
    color: rgb(255, 62, 82);
    margin-left: 5px;
  }

  .gauge-card,
  .chart-card {
    flex: 1;
    min-width: 200px;
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
    font-size: 16px;
  }

  .gauge-title,
  .chart-title {
    font-size: 16px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 15px;
    text-align: center;
  }

  .chart-title {
    font-size: 15px;
    margin-bottom: 20px;
  }

  .gauge-info {
    margin-top: 15px;
    display: flex;
    justify-content: space-around;
    font-size: 14px;
    color: #909399;
  }

  .info-item {
    display: flex;
    align-items: center;
  }

  // @media (max-width: 768px) {
  //   .gauge-charts-wrapper {
  //     flex-direction: column;
  //   }

  //   .gauge-card,
  //   .chart-card {
  //     width: 100%;
  //   }
  // }

  .tools {
    display: flex;
    align-items: center;
    .el-button {
      margin: 0 12px;
    }
    .timeType {
      margin: 0 20px;
      // letter-spacing: 8px;
      span {
        cursor: pointer;
        margin: 0 4px;
      }
      span.active,
      span:hover {
        border-bottom: 2px solid #1890ff;
        color: #1890ff;
      }
    }
  }
</style>
