<template>
  <div style="flex: 1">
    <Container :name="title" icon="cockpitItemIcon" size="operatingRevenueBg" topSize="middle">
      <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.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.detailData.completeRate}}%</span></span>
              <span style='display: inline-block;margin-left: 10px;'>差值:<span :style="{color:item.detailData.flag>0?'#30B590':'#FF9423'}" >{{item.detailData.diff}}</span></span>
            </div>
            <operatingSingleBar :detailData="item.detailData"></operatingSingleBar>
          </div>
        </div>
      </div>
    </Container>
  </div>
</template>

<script>
import Container from './container.vue'
import operatingSingleBar from './operatingSingleBar.vue'
export default {
  name: 'ProductionStatus',
  components: { Container, operatingSingleBar },
  props: {
    relatedMon: {
      type: Object,
      default: () => ({
        运费: { completeRate: 0, diff: 0, real: 0, target: 0, thb: 0 },
        全成本: { completeRate: 0, diff: 0, real: 0, target: 0, thb: 0 },
        销量: { completeRate: 0, diff: 0, real: 0, target: 0, thb: 0 }
      })
    },
    dateData: {
      type: Object,
      default: () => ({})
    },
    factory: {
      type: [String, Number],
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      chart: null,
      // 兜底数据：防止字段缺失时报错
      defaultData: {
        completeRate: 0,
        diff: 0,
        real: 0,
        target: 0,
        thb: 0
      }
    }
  },
  computed: {
    indicatorDefs() {
      return [
        { key: 'saleData', name: '销量', unit: '万㎡', route:'/salesVolumeAnalysis/salesVolumeAnalysisBase'},
        { key: 'cbData', name: '全成本', unit: '元/㎡',route:'/fullCostAnalysis/fullCostAnalysisBase'},
        { key: 'yfData', name: '运费', unit: '元/㎡',route:null}
      ]
    },
    indicators() {
      let _this = this
      const fallback = { target: 0, real: 0, completeRate: 0, diff: 0, flag: 0 }
      const list = Object.entries(_this.relatedMon).map(([title, data]) => {
        return {
          title: title,
          target: data.target,
          real: data.real,
          completeRate: data.completeRate,
          diff: data.diff
        };
      });
      return _this.indicatorDefs.map(def => {
        const data = list.find(item => item && item.title === def.name) || fallback
        const detailData = {
          ...data,
          flag: _this.getRateFlag((data || _this.defaultData).completeRate, (data || _this.defaultData).real, (data || _this.defaultData).target),
        }
        return {
          ...def,
          detailData,
          sortValue: Number((data && data.real) ?? 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: {
    relatedMon: {
      handler(newValue) {
        this.updateChart()
      },
      immediate: true, // 初始化时立即执行
      deep: true
    }
  },
  mounted() {
    // 初始化图表
    this.$nextTick(() => this.updateChart())
  },
  methods: {
    handleDashboardClick(path) {
      this.$router.push({
        path: path,
        query: {
          factory: this.$route.query.factory ? this.$route.query.factory : this.factory,
          dateData: this.dateData
        }
      })
    },
    /**
     * 判断完成率对应的flag值（<100为0，≥100为1）
     * @param {number} rate 完成率（原始值，如89代表89%）
     * @returns {0|1} flag值
     */
    getRateFlag(rate, real, target) {
      if (isNaN(rate) || rate === null || rate === undefined) return 0;

      // 1. 完成率 >= 100 => 达标
      if (rate >= 100) return 1;

      // 2. 完成率 = 0 且 (目标值=0 或 实际值=目标值=0) => 达标
      if (rate === 0 && target === 0) return 1;

      // 其他情况 => 未达标
      return 0;
    },

    /**
     * 图表更新方法：可在这里补充全局的图表刷新逻辑
     * 若子组件内部已监听 chartData 变化，此方法可留空或补充额外逻辑
     */
    updateChart() {
      // console.log('数据更新，当前relatedMon:', this.relatedMon)
      // // 打印各维度的flag值，方便调试
      // console.log('销量flag:', this.getRateFlag(this.relatedMon.销量.completeRate))
      // console.log('成本flag:', this.getRateFlag(this.relatedMon.成本.completeRate))
      // console.log('运费flag:', this.getRateFlag(this.relatedMon.运费.completeRate))
    }
  }
}
</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: 250px;
  height: 205px;
  background: #F9FCFF;
  padding: 16px 0 0 10px;
  box-sizing: border-box; // 防止内边距撑大容器

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

  // 图表容器样式：适配高度
  .chart-wrap {
    width: calc(100% - 16px); // 适配左侧内边距
    height: calc(100% - 46px); // 减去标题高度和间距
  }

  .number {
    display: flex;
    align-items: center;
    gap: 6px;
    height: 32px;
    font-family: YouSheBiaoTiHei;
    font-size: 32px;
    color: #0B58FF;
    line-height: 32px;
    letter-spacing: 2px;
    white-space: nowrap;
  }

  .mom {
    width: 97px;
    height: 18px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 18px;
    color: #000000;
    line-height: 18px;
    letter-spacing: 1px;
    z-index: 1000;
  }
}
</style>
