<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" style="text-align: center;">
      <el-form-item style="width: 208px; display: inline-block;">
        <div style="display: flex; align-items: center; justify-content: center;">
          <el-button icon="ArrowLeft" @click="navigateDay(-1)" size="small" style="margin-right: 15px;"></el-button>
          <el-date-picker clearable
                          v-model="queryParams.dataDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择日期"
                          style="width: 130px"
                          @change="handleQuery">
          </el-date-picker>
          <el-button icon="ArrowRight" @click="navigateDay(1)" size="small" style="margin-left: 15px;"></el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 产线选择 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="24">
        <el-card>
          <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">
            <span>选择产线进行对比：</span>
            <el-button size="small" @click="selectAllLines">全选</el-button>
            <el-button size="small" @click="invertSelection">反选</el-button>
            <el-checkbox-group v-model="selectedLines" @change="getList" style="padding-left: 30px;">
              <el-checkbox v-for="line in allLines" :key="line" :label="line">{{ line }}</el-checkbox>
            </el-checkbox-group>
          </div>
<!--          <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">-->
<!--            <el-checkbox-group v-model="selectedLines" @change="getList">-->
<!--              <el-checkbox v-for="line in allLines" :key="line" :label="line">{{ line }}</el-checkbox>-->
<!--            </el-checkbox-group>-->
<!--          </div>-->
          <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px; margin-bottom: 10px;">
            <span>选择指标：</span>
            <el-button size="small" @click="selectAllMetrics">全选</el-button>
            <el-button size="small" @click="invertMetrics">反选</el-button>
            <el-checkbox-group v-model="selectedMetrics" @change="updateChart" style="padding-left: 30px;">
              <el-checkbox label="开机率">开机率</el-checkbox>
              <el-checkbox label="温度">温度</el-checkbox>
              <el-checkbox label="速度">速度</el-checkbox>
              <el-checkbox label="电量">电量</el-checkbox>
              <el-checkbox label="电流">电流</el-checkbox>
            </el-checkbox-group>
          </div>
<!--          <div style="display: flex; align-items: center; flex-wrap: wrap; gap: 10px;">-->
<!--            <el-checkbox-group v-model="selectedMetrics" @change="updateChart">-->
<!--              <el-checkbox label="开机率">开机率</el-checkbox>-->
<!--              <el-checkbox label="温度">温度</el-checkbox>-->
<!--              <el-checkbox label="速度">速度</el-checkbox>-->
<!--              <el-checkbox label="电量">电量</el-checkbox>-->
<!--              <el-checkbox label="电流">电流</el-checkbox>-->
<!--            </el-checkbox-group>-->
<!--          </div>-->
        </el-card>
      </el-col>
    </el-row>

    <!-- 折线图和表格左右布局 -->
    <el-row :gutter="20">
      <!-- 左侧折线图 -->
      <el-col :span="12">
        <el-card style="margin-bottom: 20px;">
          <div ref="chartRef" style="width: 100%; height: 520px;"></div>
        </el-card>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="12">
        <el-card style="margin-bottom: 20px;">
          <el-table :data="rzLineList" height="520" :span-method="spanMethod">
            <el-table-column label="小时" align="center" prop="hour" width="60" />
            <el-table-column label="产线" align="center" prop="line" width="60" />
            <el-table-column label="开机率(%)" align="center" prop="openRate" />
            <el-table-column label="温度(°C)" align="center" prop="tmp" />
            <el-table-column label="速度(米/min)" align="center" prop="speed" />
            <el-table-column label="电量(kW·h)" align="center" prop="energy" />
            <el-table-column label="电流(A)" align="center" prop="amp" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="RzLine">
import * as echarts from 'echarts';
import { listRzLine, getRzLine, delRzLine, addRzLine, updateRzLine } from "@/api/dyeing/rzLine";

const { proxy } = getCurrentInstance();

const rzLineList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const chartRef = ref(null);
let chartInstance = null;

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10000,
    dataDate: new Date(new Date().getTime() - 24 * 60 * 60 * 1000).Format('yyyy-MM-dd'),
    hour: null,
    lines: null,
    openRate: null,
    length: null,
    tmp: null,
    speed: null,
    energy: null,
    amp: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    remark: null
  },
  rules: {
  }
});

const selectedMetrics = ref(['开机率', '温度', '速度', '电量', '电流']);
const selectedLines = ref(['1', '2', '3', '4', '5', '6', '7', '8']);
const allLines = ref(['1', '2', '3', '4', '5', '6', '7', '8']);

const { queryParams, form, rules } = toRefs(data);

// 按产线分组的数据
const groupedRzLineList = computed(() => {
  const grouped = {};
  rzLineList.value.forEach(item => {
    if (!grouped[item.line]) {
      grouped[item.line] = [];
    }
    grouped[item.line].push(item);
  });
  // 按产线编号排序
  const sortedGrouped = {};
  Object.keys(grouped).sort().forEach(key => {
    sortedGrouped[key] = grouped[key];
  });
  return sortedGrouped;
});

// 合并单元格处理函数
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) { // 小时列
    // 获取当前行小时值
    const currentHour = row.hour;

    // 计算当前小时值第一次出现的位置
    let firstIndex = -1;
    for (let i = 0; i < rzLineList.value.length; i++) {
      if (rzLineList.value[i].hour === currentHour) {
        firstIndex = i;
        break;
      }
    }

    // 如果当前行是该小时值第一次出现的位置
    if (firstIndex === rowIndex) {
      // 计算该小时值连续出现的次数
      let spanCount = 0;
      for (let i = firstIndex; i < rzLineList.value.length; i++) {
        if (rzLineList.value[i].hour === currentHour) {
          spanCount++;
        } else {
          break;
        }
      }
      return [spanCount, 1];
    } else {
      // 如果不是第一次出现，隐藏该单元格
      return [0, 0];
    }
  }
  return [1, 1]; // 其他列不合并
};
function navigateDay(offset) {
  const currentDate = new Date(queryParams.value.dataDate);
  currentDate.setDate(currentDate.getDate() + offset);
  queryParams.value.dataDate = currentDate.toISOString().split('T')[0];
  handleQuery();
}
/** 查询染整线产线小时统计数据列表 */
function getList() {
  // 检查是否选择了产线
  if (selectedLines.value.length === 0) {
    proxy.$modal.msgWarning("请至少选择一条产线进行对比");
    return;
  }

  // 设置查询参数
  queryParams.value.lines = selectedLines.value.join(',');

  loading.value = true;
  listRzLine(queryParams.value).then(response => {
    // 按小时排序
    rzLineList.value = response.rows.sort((a, b) => {
      if (a.hour !== b.hour) {
        return a.hour - b.hour;
      }
      return a.line - b.line;
    });
    total.value = response.total;
    loading.value = false;

    // 更新图表
    nextTick(() => {
      updateChart();
    });
  });
}

// 初始化图表
function initChart() {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value);
  }
}

// 更新图表
function updateChart() {
  if (!chartInstance || !rzLineList.value.length) {
    return;
  }

  // 按产线分组数据，只处理已选择的产线
  const lineMap = new Map();
  rzLineList.value.forEach(item => {
    // 只处理已选择的产线
    if (selectedLines.value.includes(item.line)) {
      if (!lineMap.has(item.line)) {
        lineMap.set(item.line, []);
      }
      lineMap.get(item.line).push(item);
    }
  });

  // 获取所有唯一的时间点
  const allTimePoints = [...new Set(rzLineList.value.map(item =>
    `${item.dataDate} ${item.hour.toString().padStart(2, '0')}:00`))].sort();

  // 准备图表数据
  const series = [];
  const legendData = [];

  // 为每个产线生成数据系列
  for (let [line, items] of lineMap) {
    // 为每个产线生成选定指标的数据系列
    const dataMap = new Map();
    items.forEach(item => {
      const timePoint = `${item.dataDate} ${item.hour.toString().padStart(2, '0')}:00`;
      dataMap.set(timePoint, item);
    });

    // 基于统一时间轴生成数据
    const openRateData = selectedMetrics.value.includes('开机率') ? allTimePoints.map(timePoint => {
      const item = dataMap.get(timePoint);
      return item && item.openRate !== null ? parseFloat(item.openRate) : null;
    }) : [];

    const tmpData = selectedMetrics.value.includes('温度') ? allTimePoints.map(timePoint => {
      const item = dataMap.get(timePoint);
      return item && item.tmp !== null ? parseFloat(item.tmp) : null;
    }) : [];

    const speedData = selectedMetrics.value.includes('速度') ? allTimePoints.map(timePoint => {
      const item = dataMap.get(timePoint);
      return item && item.speed !== null ? parseFloat(item.speed) : null;
    }) : [];

    const energyData = selectedMetrics.value.includes('电量') ? allTimePoints.map(timePoint => {
      const item = dataMap.get(timePoint);
      return item && item.energy !== null ? parseFloat(item.energy) : null;
    }) : [];

    const ampData = selectedMetrics.value.includes('电流') ? allTimePoints.map(timePoint => {
      const item = dataMap.get(timePoint);
      return item && item.amp !== null ? parseFloat(item.amp) : null;
    }) : [];

    // 添加产线+指标的数据系列
    if (selectedMetrics.value.includes('开机率')) {
      legendData.push(`${line}-开机率`);
      series.push({
        name: `${line}-开机率`,
        type: 'line',
        data: openRateData,
        smooth: true,
        showSymbol: false
      });
    }

    if (selectedMetrics.value.includes('温度')) {
      legendData.push(`${line}-温度`);
      series.push({
        name: `${line}-温度`,
        type: 'line',
        data: tmpData,
        smooth: true,
        showSymbol: false
      });
    }

    if (selectedMetrics.value.includes('速度')) {
      legendData.push(`${line}-速度`);
      series.push({
        name: `${line}-速度`,
        type: 'line',
        data: speedData,
        smooth: true,
        showSymbol: false
      });
    }

    if (selectedMetrics.value.includes('电量')) {
      legendData.push(`${line}-电量`);
      series.push({
        name: `${line}-电量`,
        type: 'line',
        data: energyData,
        smooth: true,
        showSymbol: false
      });
    }

    if (selectedMetrics.value.includes('电流')) {
      legendData.push(`${line}-电流`);
      series.push({
        name: `${line}-电流`,
        type: 'line',
        data: ampData,
        smooth: true,
        showSymbol: false
      });
    }
  }

  const option = {
    title: {
      text: '前整车间产线对比',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = params[0].axisValue + '<br/>';
        params.forEach(param => {
          let valueText = '';
          if (param.seriesName.includes('开机率')) {
            valueText = param.value !== null ? param.value + ' (%)' : '无数据';
          } else if (param.seriesName.includes('温度')) {
            valueText = param.value !== null ? param.value + ' (°C)' : '无数据';
          } else if (param.seriesName.includes('速度')) {
            valueText = param.value !== null ? param.value + ' (米/min)' : '无数据';
          } else if (param.seriesName.includes('电量')) {
            valueText = param.value !== null ? param.value + ' (kW·h)' : '无数据';
          } else if (param.seriesName.includes('电流')) {
            valueText = param.value !== null ? param.value + ' (A)' : '无数据';
          } else {
            valueText = param.value !== null ? param.value : '无数据';
          }
          result += `<div style="display:flex;align-items:center;">
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>
            ${param.seriesName}: ${valueText}
          </div>`;
        });
        return result;
      }
    },
    legend: [
      ...Array.from(lineMap.keys()).map((line, index) => {
        const lineLegendData = [];
        if (selectedMetrics.value.includes('开机率')) lineLegendData.push(`${line}-开机率`);
        if (selectedMetrics.value.includes('温度')) lineLegendData.push(`${line}-温度`);
        if (selectedMetrics.value.includes('速度')) lineLegendData.push(`${line}-速度`);
        if (selectedMetrics.value.includes('电量')) lineLegendData.push(`${line}-电量`);
        if (selectedMetrics.value.includes('电流')) lineLegendData.push(`${line}-电流`);

        return {
          data: lineLegendData,
          top: 40 + index * 25,
          left: 'center',
          textStyle: {
            fontSize: 10
          },
          itemWidth: 10,
          itemHeight: 10
        };
      })
    ],
    grid: {
      left: '3%',
      right: '4%',
      top: '25%',
      bottom: 20,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allTimePoints
    },
    yAxis: {
      type: 'value',
      name: ''
    },
    series: series
  };

  chartInstance.setOption(option, true);
}

// 窗口大小改变时重置图表大小
function resizeChart() {
  if (chartInstance) {
    chartInstance.resize();
  }
}

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart);

  // 默认选择所有产线
  selectedLines.value = [...allLines.value];

  // 初始加载数据
  getList();
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart);
  if (chartInstance) {
    chartInstance.dispose();
  }
});

onActivated(() => {
  resizeChart();
});

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    dataDate: null,
    hour: null,
    line: null,
    openRate: null,
    length: null,
    tmp: null,
    speed: null,
    energy: null,
    amp: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    remark: null
  };
  proxy.resetForm("rzLineRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  // 检查查询条件
  if (!queryParams.value.dataDate) {
    proxy.$modal.msgWarning("请选择日期");
    return;
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  // 设置默认日期为当前日期
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  const day = now.getDate().toString().padStart(2, '0');
  queryParams.value.dataDate = `${year}-${month}-${day}`;

  // 默认选择所有产线
  selectedLines.value = [...allLines.value];

  handleQuery();
}

// 全选产线
function selectAllLines() {
  selectedLines.value = [...allLines.value];
  getList();
}

// 反选产线
function invertSelection() {
  const newSelectedLines = [];
  allLines.value.forEach(line => {
    if (!selectedLines.value.includes(line)) {
      newSelectedLines.push(line);
    }
  });
  selectedLines.value = newSelectedLines;
  getList();
}

// 全选指标
function selectAllMetrics() {
  selectedMetrics.value = ['开机率', '温度', '速度', '电量', '电流'];
  updateChart();
}

// 反选指标
function invertMetrics() {
  const allMetrics = ['开机率', '温度', '速度', '电量', '电流'];
  const newSelectedMetrics = [];
  allMetrics.forEach(metric => {
    if (!selectedMetrics.value.includes(metric)) {
      newSelectedMetrics.push(metric);
    }
  });
  selectedMetrics.value = newSelectedMetrics;
  updateChart();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加染整线产线小时统计数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getRzLine(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改染整线产线小时统计数据";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["rzLineRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateRzLine(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRzLine(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除染整线产线小时统计数据编号为"' + _ids + '"的数据项？').then(function() {
    return delRzLine(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dyeing/rzLine/export', {
    ...queryParams.value
  }, `rzLine_${new Date().getTime()}.xlsx`)
}

getList();
</script>
