<template>
  <div style="flex: 1">
    <Container :isShowTab="true" :name="title" icon="cockpitItemIcon" size="opLargeBg" topSize="large"
      @tabChange="handleChange">
      <div class="kpi-content" style="padding: 14px 16px; display: flex; width: 100%;">
        <div class="topItem-container" style="display: flex; gap: 8px">
          <div
            v-for="item in sortedIndicators"
            :key="item.key"
            class="dashboard"
            @click="item.route && handleDashboardClick(item.name,item.route)"
          >
            <div class="title">
              {{ item.name }}·{{ item.unit }}
            </div>
            <div style='font-size: 14px;text-align: right;padding-right: 5px;'>
              <span>完成率:<span style='color: #0B58FF;'>{{item.data.proportion}}%</span></span>
              <span style='display: inline-block;margin-left: 10px;'>差值:<span :style="{color:item.data.completed>0?'#30B590':'#FF9423'}" >{{item.data.diffValue}}</span></span>
            </div>
            <operatingSingleBar :detailData="item.data"></operatingSingleBar>
          </div>
        </div>
      </div>
    </Container>
  </div>
</template>

<script>
import Container from '../components/container.vue'
import operatingSingleBar from './operatingSingleBar.vue'

export default {
  name: 'GasWaterProductionStatus', // 与第二个组件区分命名
  components: { Container, operatingSingleBar },
  props: {
    // 完全对齐第二个组件的props结构，数据格式统一
    relatedData: {
      type: Object,
      default: () => ({
        relatedMon: [], // 月度数据（数组格式，存储各物料项）
        relatedTotal: [] // 累计数据（数组格式，存储各物料项）
      })
    },
    dateData: {
      type: Object,
      default: () => ({ })
    },
    title: {
      type: String,
      default: ''
    },
    factory: {
      type: [String, Number],
      default: ''
    },
    month: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      chart: null,
      activeData: this.relatedData.relatedMon || [], // 核心激活数据集（默认月度，与第二个组件一致）
    }
  },
  computed: {
    indicatorDefs() {
      return [
        { key: 'naturalGas', name: '天然气', unit: '元/吨',route:'singleCombustible'},
        { key: 'lng', name: 'LNG液化天然气', unit: '元/吨',route:'singleCombustible'},
        { key: 'heavyOil', name: '重油', unit: '元/吨',route:'singleCombustible'},
        { key: 'water', name: '水', unit: '元/吨',route:'singleCombustible'}
      ]
    },
    indicators() {
      const fallback = { targetValue: 0, value: 0, completed: 0, diffValue: 0 }
      const list = (Array.isArray(this.activeData) ? this.activeData : [])

      return this.indicatorDefs.map(def => {
        const data = list.find(item => item && item.name.includes(def.name)) || fallback
        return {
          ...def,
          data,
          sortValue: Number((data && data.value) ?? 0)
        }
      })
    },
    sortedIndicators() {
      const unitOrder = ['元/吨']
      const unitRank = (u) => {
        const idx = unitOrder.indexOf(u)
        return idx === -1 ? 999 : idx
      }

      return this.indicators.slice().sort((a, b) => {
        const ur = unitRank(a.unit) - unitRank(b.unit)
        if (ur !== 0) return ur
        const vr = (b.sortValue ?? -Infinity) - (a.sortValue ?? -Infinity)
        if (vr !== 0) return vr
        return String(a.key).localeCompare(String(b.key))
      })
    }
  },
  watch: {
    // 对齐第二个组件：深度监听relatedData变化，同步更新激活数据集
    relatedData: {
      handler(newVal) {
        this.activeData = newVal.relatedMon || [];
      },
      immediate: true, // 挂载时立即执行
      deep: true // 深度监听对象内部变化
    }
  },
  mounted() {
    console.log('燃气水组件挂载时的激活数据：', this.activeData);
  },
  methods: {
    // 新增tab切换处理函数：和第二个组件逻辑完全一致，切换月度/累计数据
    handleChange(value) {
      console.log('Tab 切换值：', value);
      // 根据tab值更新激活数据集
      if (value === 'month') {
        this.activeData = this.relatedData.relatedMon || [];
      } else {
        this.activeData = this.relatedData.relatedTotal || [];
      }
      console.log('当前激活数据集：', this.activeData);
    },

    // 优化点击事件：对齐第二个组件，接收物料名和路由路径，修复原路由参数错误
    handleDashboardClick(material, path) {

      // 2. 修复原路由跳转错误：month放入query中（原代码month直接写在路由配置里无效）
      this.$router.push({
        path: path,
        query: {
          name: material,
          month: this.month,
          factory: this.$route.query.factory ? this.$route.query.factory : this.factory,
          dateData: this.dateData
        }
      });
    }
  }
}
</script>

<style lang='scss' scoped>
/* 完全对齐第二个组件样式，统一视觉效果 */
.scroll-container {
  max-height: 210px;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 10px 0;

  &::-webkit-scrollbar {
    display: none;
  }

  scrollbar-width: none;
  -ms-overflow-style: none;
}

.dashboard {
  width: 390px;
  height: 205px;
  background: #F9FCFF;
  padding: 16px 0 0 10px;
  flex-shrink: 0; // 固定宽度，不被挤压（与第二个组件一致）
  cursor: pointer; // 鼠标悬浮手型（保留原点击反馈）
  transition: all 0.2s ease; // 过渡动画（保留原样式）

  // 悬浮样式（保留原交互效果）
  // &:hover {
  //   background: #F0F8FF;
  //   box-shadow: 0 2px 8px rgba(11, 88, 255, 0.1);
  // }

  // // 选中状态样式（可选，与第二个组件风格统一）
  // &.active {
  //   background: #E8F4FF;
  //   border: 1px solid #0B58FF;
  // }

  .title {
    height: 18px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #000000;
    line-height: 18px;
    letter-spacing: 2px;
    text-align: left;
    font-style: normal;
  }

  .number {
    display: flex;
    align-items: center;
    gap: 30px;
    height: 32px;
    font-family: YouSheBiaoTiHei;
    font-size: 32px;
    color: #0B58FF;
    line-height: 32px;
    letter-spacing: 2px;
    text-align: left;
    font-style: normal;
  }

  // .line {
  //   width: 280px; // 适配310px宽度，避免图表溢出（与第二个组件一致）
  //   height: 150px; // 图表高度与第二个组件统一
  // }
}

/* 隐藏横向滚动条，与第二个组件样式完全统一 */
.topItem-container::-webkit-scrollbar {
  display: none;
}

.topItem-container {
  scrollbar-width: none;
  -ms-overflow-style: none;
}
</style>
