<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="dataDate">
        <el-date-picker clearable
                        v-model="queryParams.dataDate"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择日期" @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="机台号" prop="deviceId">
        <el-select
            v-model="queryParams.deviceId"
            placeholder="请选择机台号"
            filterable
            style="width: 80px"
            @change="handleQuery"
        >
          <el-option
              v-for="item in deviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时段" prop="remark">
        <el-select v-model="queryParams.remark" placeholder="选择时段" style="width: 180px" @change="handleQuery">
          <el-option
              v-for="dict in in_out_time"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="success" @click="viewTrend">查看近5日织造米数</el-button>
      </el-form-item>
    </el-form>

    <!-- 图表弹窗 -->
    <el-dialog title="近5日织造米数趋势图" v-model="chartDialogVisible" width="800px" append-to-body>
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeChartDialog">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-table v-loading="loading" :data="calcSpecList" show-summary :summary-method="getSummaries"
              @selection-change="handleSelectionChange">
      <el-table-column label="日期" align="center" prop="dataDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.dataDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="小时" align="center" prop="hour"/>
      <el-table-column label="机台号" align="center" prop="deviceId"/>
      <el-table-column label="织造米数" align="center" prop="length"/>
      <el-table-column label="规格" align="center" prop="spec"/>
      <el-table-column label="毛高" align="center" prop="height"/>
      <el-table-column label="米克重" align="center" prop="mick"/>
      <el-table-column label="密度" align="center" prop="density"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">核对</el-button>
              </template>
            </el-table-column>
    </el-table>

    <!-- 添加或修改按配方1小时统计数据对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="calcSpecRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="dataDate">
          <el-date-picker disabled
                          v-model="form.dataDate"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="小时" prop="hour">
          <el-input v-model="form.hour" disabled />
        </el-form-item>
        <el-form-item label="机台号" prop="deviceId">
          <el-input v-model="form.deviceId" disabled />
        </el-form-item>
        <el-form-item label="织造米数" prop="length">
          <el-input-number v-model="form.length" placeholder="请输入织造米数" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="密度" prop="density">
          <el-input-number v-model="form.density" placeholder="请输入密度" style="width: 180px"/>
        </el-form-item>
        <el-form-item label="规格" prop="spec">
          <el-input v-model="form.spec" disabled/>
        </el-form-item>
        <el-form-item label="毛高" prop="height">
          <el-input v-model="form.height" disabled/>
        </el-form-item>
        <el-form-item label="米克重" prop="mick">
          <el-input v-model="form.mick" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CalcSpec">
import {addCalcSpec, delCalcSpec, getCalcSpec, listCalcSpec, updateCalcSpec,trend} from "@/api/calc/calcSpec";
import {listDevice} from "@/api/biz/device"
import * as echarts from 'echarts';
import { nextTick } from 'vue';

const {proxy} = getCurrentInstance();
const {in_out_time} = proxy.useDict('in_out_time');
const calcSpecList = 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 deviceOptions = ref([]);
const chartRef = ref(null);
let chartInstance = null;
const chartDialogVisible = ref(false);
const trendData = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    dataDate: new Date(new Date().getTime() - 31 * 60 * 60 * 1000).Format('yyyy-MM-dd'),
    hour: null,
    deviceId: null,
    length: null,
    spec: null,
    height: null,
    mick: null,
    density: null,
    price: null,
    remark: null
  },
  rules: {
    density: [
      { required: true, message: "密度不能为空", trigger: "blur" },
      { type: "number", message: "密度必须为数字值", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value <= 0) {
            callback(new Error('密度必须大于0'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ],
    length: [
      { required: true, message: "织造米数不能为空", trigger: "blur" },
      { type: "number", message: "织造米数必须为数字值", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value <= 0) {
            callback(new Error('织造米数必须大于0'));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  }
});

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

function getDevice() {
  listDevice({online: 1, pageNum: 1, pageSize: 1000}).then(response => {
    deviceOptions.value = response.rows.map(item => ({
      value: item.deviceId,
      label: item.deviceId
    }));
  }).catch(error => {
    console.error('获取机台号列表失败:', error);
    proxy.$modal.notifyError('获取机台号列表失败');
  });
}


/** 查询按配方1小时统计数据列表 */
function getList() {
  loading.value = true;
  if (!queryParams.value.deviceId) {
    queryParams.value.deviceId = 1;
  }
  if (!queryParams.value.remark) {
    queryParams.value.remark = '7-19';
  }
  listCalcSpec(queryParams.value).then(response => {
    calcSpecList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/**查询趋势*/
function viewTrend(){
  trend(queryParams.value).then(response => {
    // 保存数据并显示图表弹窗
    trendData.value = response;
    chartDialogVisible.value = true;
    // 等待DOM更新后初始化图表
    nextTick(() => {
      initChart(response);
    });
  });
}

// 关闭图表弹窗
function closeChartDialog() {
  chartDialogVisible.value = false;
  // 销毁图表实例
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
}

// 初始化图表
function initChart(data) {
  // 销毁之前的图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 初始化新的图表实例
  chartInstance = echarts.init(chartRef.value);

  console.log('传入initChart的数据:', data); // 调试信息

  // 处理数据 - 修正数据访问路径
  let responseData = data.data.data;

  const timestamps = responseData.timestamps || [];
  const values = responseData.values || [];

  console.log('提取的原始数据:', { timestamps, values }); // 调试信息

  // 将时间戳转换为日期字符串 (mm-dd hh:mm格式)
  const dates = timestamps.map(timestamp => {
    const date = new Date(timestamp);
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hours}:${minutes}`;
  });

  // 提取数值（处理嵌套数组）
  const chartValues = [];
  const validDates = [];

  values.forEach((item, index) => {
    // 检查是否有足够的数据点
    if (Array.isArray(item) && item.length > 0) {
      // 获取第一个元素并尝试转为数字
      const rawValue = item[0];
      const numericValue = parseFloat(rawValue);

      // 检查转换后的值是否有效
      if (!isNaN(numericValue)) {
        chartValues.push(numericValue);
        validDates.push(dates[index]);
      } else if (typeof rawValue === 'number' && !isNaN(rawValue)) {
        // 如果本身就是数字
        chartValues.push(rawValue);
        validDates.push(dates[index]);
      }
    }
  });

  console.log('处理后的图表数据:', { validDates, chartValues }); // 调试信息

  // 如果没有有效数据，显示提示
  if (validDates.length === 0 && chartValues.length === 0) {
    chartInstance.setOption({
      title: {
        text: '暂无有效数据',
        left: 'center',
        top: 'center'
      }
    });
    return;
  }

  // 计算默认显示的时间范围（根据选择的日期和时段）
  let startIndex = 0;
  let endIndex = validDates.length - 1;

  if (queryParams.value.dataDate && queryParams.value.remark) {
    // 解析时段，例如 "7-19" 或 "23-7"
    const timeRange = queryParams.value.remark.split('-');
    if (timeRange.length === 2) {
      const startTime = parseInt(timeRange[0]);
      const endTime = parseInt(timeRange[1]);

      // 构造选择的日期
      const selectedDate = new Date(queryParams.value.dataDate);
      const month = (selectedDate.getMonth() + 1).toString().padStart(2, '0');
      const day = selectedDate.getDate().toString().padStart(2, '0');

      // 判断是否是跨天时段（如23-7）
      if (startTime > endTime) {
        // 跨天时段处理，例如 23-7 表示当天23点到次日7点
        // 查找当天23点开始的数据
        const startDateTime = `${month}-${day} ${startTime.toString().padStart(2, '0')}:00`;
        const startTimeIndex = validDates.findIndex(date => date.startsWith(startDateTime));
        if (startTimeIndex !== -1) {
          startIndex = startTimeIndex;
        }

        // 查找次日7点的数据
        const nextDay = new Date(selectedDate);
        nextDay.setDate(nextDay.getDate() + 1);
        const nextMonth = (nextDay.getMonth() + 1).toString().padStart(2, '0');
        const nextDayStr = nextDay.getDate().toString().padStart(2, '0');
        const endDateTime = `${nextMonth}-${nextDayStr} ${endTime.toString().padStart(2, '0')}:00`;
        const endTimeIndex = validDates.findIndex(date => date.startsWith(endDateTime));
        if (endTimeIndex !== -1) {
          endIndex = endTimeIndex;
        }
      } else {
        // 正常时段处理，例如 7-19 表示当天7点到19点
        // 查找开始时间索引
        const startDateTime = `${month}-${day} ${startTime.toString().padStart(2, '0')}:00`;
        const startTimeIndex = validDates.findIndex(date => date.startsWith(startDateTime));
        if (startTimeIndex !== -1) {
          startIndex = startTimeIndex;
        }

        // 查找结束时间索引
        const endDateTime = `${month}-${day} ${endTime.toString().padStart(2, '0')}:00`;
        const endTimeIndex = validDates.findIndex(date => date.startsWith(endDateTime));
        if (endTimeIndex !== -1) {
          endIndex = endTimeIndex;
        } else {
          // 如果找不到确切的结束时间，尝试查找最接近的时间点
          for (let i = validDates.length - 1; i >= 0; i--) {
            if (validDates[i].startsWith(`${month}-${day}`)) {
              endIndex = i;
              break;
            }
          }
        }
      }

      // 确保索引范围合理
      if (startIndex >= endIndex) {
        endIndex = Math.min(startIndex + 10, validDates.length - 1); // 默认显示10个点
      }
    }
  }

  // 配置图表选项 - 遵循项目规范
  const option = {
    title: {
      text: '近5日织造米数趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        const date = params[0].axisValue;
        const value = params[0].data;
        return `${date}<br/>织造米数: ${value}`;
      }
    },
    dataZoom: [
      {
        type: 'inside',
        startValue: startIndex,
        endValue: endIndex
      },
      {
        type: 'slider',
        startValue: startIndex,
        endValue: endIndex,
        bottom: 10
      }
    ],
    xAxis: {
      type: 'category',
      data: validDates.length > 0 ? validDates : dates, // 如果有有效日期则使用，否则使用全部日期
      name: '时间',
      axisLabel: {
        formatter: '{value}',
        rotate: 45 // 旋转标签以避免重叠
      },
      splitLine: {
        show: false  // 遵循规范：不显示网格线
      }
    },
    yAxis: {
      type: 'value',
      name: '织造米数',
      splitLine: {
        show: false  // 遵循规范：不显示网格线
      }
    },
    series: [{
      data: chartValues.length > 0 ? chartValues : values, // 如果有处理后的数据则使用，否则使用原始数据
      type: 'line',
      smooth: true,
      showSymbol: false,  // 遵循规范：不显示数据点小圆圈
      itemStyle: {
        color: '#409EFF'
      },
      markPoint: {
        data: [
          {type: 'max', name: '最大值', itemStyle: {color: '#F56C6C'}},
          {type: 'min', name: '最小值', itemStyle: {color: '#67C23A'}}
        ]
      },
      markLine: {
        data: [
          {type: 'average', name: '平均值'}
        ]
      }
    }]
  };

  // 设置图表配置
  chartInstance.setOption(option);

  // 监听窗口大小变化，自适应图表
  window.addEventListener('resize', () => {
    chartInstance.resize();
  });
}

//自定义方法
function getSummaries(param) {
  const {columns, data} = param;
  const sums = {};
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index != 3) {
      sums[index] = '';
      return;
    }
    const values = data.map(item => Number(item[column.property]));
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] = sums[index].toFixed(2);
    } else {
      sums[index] = 'N/A';
    }
  });
  return sums;
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    dataDate: null,
    hour: null,
    deviceId: null,
    length: null,
    spec: null,
    height: null,
    mick: null,
    density: null,
    price: null,
    remark: null
  };
  proxy.resetForm("calcSpecRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  getDevice();
  handleQuery();
}

// 多选框选中数据
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 = "添加按配方1小时统计数据";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCalcSpec(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "产量数据核对";
  });
}

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

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

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

getDevice();
getList();
</script>
