<template>
  <view>
    <view class="example-body">
      <!-- 选择月份 -->
      <el-date-picker
        v-model="monthValue"
        type="month"
        placeholder="选择月"
        @change="onMonthChange" 
        format="yyyy-MM"  ></el-date-picker>
    </view>
    
    <!-- 表格显示 -->
    <el-table :data="tableData"  show-summary style="width: 100%">
      <el-table-column prop="category" label="类别" fixed="left" width="100"></el-table-column>
      <el-table-column prop="total_monthly_summarys" label="当月汇总" fixed="left" width="100"></el-table-column>
      <!-- 动态生成的日期列 -->
      <el-table-column 
        v-for="day in days" 
        :key="day" 
        :prop="day" 
        :label="day" 
        :width="150" 
        align="center" 
        :formatter="formatNullToZero">
        <template v-slot="scope">
          <span style="margin-left: 10px">{{ scope.row[day] || 0 }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 提示文字 -->
    <view class="scroll-hint">
      <p>*可左右滑动查看</p>
    </view>

    <!-- 图表显示 -->
    <view class="charts-box">
      <qiun-data-charts 
        type="line"
        :opts="opts"
        :chartData="chartData"
        :ontouch="true"
      />
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      monthValue: '',  // 选择的月份，初始化为空
      tableData: [],
      days: [],
      chartData: {},
      categories: [],
      series: [],
      opts: {
        color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
        padding: [15, 10, 0, 15],
        enableScroll: true,
        legend: {},
        xAxis: {
          disableGrid: true,
          scrollShow: true,
          itemCount: 4
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2
        },
        extra: {
          line: {
            type: "straight",
            width: 2,
            activeType: "hollow"
          }
        }
      }
    };
  },
  mounted() {
    // 初始化时设置默认月份为当前月份
    const currentMonth = new Date().toISOString().substr(0, 7);  // 获取当前月份 (格式: yyyy-MM)
    this.monthValue = currentMonth;  // 设置默认月份
    this.getDaysInCurrentMonthDatas(currentMonth);  // 加载默认月份数据
  },
  methods: {
    // 计算当前月1号到月底的所有日期
    getDaysInCurrentMonthDatas(monthValue) {
		if (typeof monthValue !== 'string') {
		        monthValue = String(monthValue); // 强制转换为字符串
		      }
      const [year, month] = monthValue.split('-');  // 分离年和月
      const daysInMonth = new Date(year, month, 0).getDate();  // 获取该月的天数
      this.days = [];
      
      for (let day = 1; day <= daysInMonth; day++) {
        const formattedDate = `${year}-${month < 10 ? '' + month : month}-${day < 10 ? '0' + day : day}`;
        this.days.push(formattedDate);
      }
    console.log(monthValue)
      // 请求数据
      uni.request({
        url: `/prod-api/mes/reportWork/getmonthProductionSut?pageNum=1&pageSize=50&monthValue=${monthValue}`,
        header: {
          Poolname: 'ds_1000'
        },
        success: (res) => {
          const datas = res.data.data.mapList_two || [];
          if (datas.length > 0) {
            datas.forEach(row => {
              let totalSummary = 0;
              const dailyValues = [];
              this.days.forEach(day => {
                const value = row[day] || 0;
                totalSummary += value;
                dailyValues.push(value);
              });
              row.total_monthly_summarys = totalSummary;
            });
          }

          this.tableData = datas;
          this.categories = this.days;
          
          // 动态生成 series，每个种类一个系列
          this.series = datas.map(row => {
            return {
              name: row.category || '未知品类',  // 使用类别名称
              data: this.days.map(day => row[day] || 0) // 每个日期对应的数据
            };
          });

          // 更新 chartData
          this.chartData = {
            categories: this.categories,  // 横轴日期
            series: this.series           // 每条线表示一种类别
          };

          this.$nextTick(() => {
            this.chartData = { ...this.chartData };  // 确保 chartData 变化被捕获
          });
        }
      });
    },

    // 监听月份变化，更新数据
    onMonthChange(newMonth) {
		  // 假设 newMonth 是 Date 对象
		  const year = newMonth.getFullYear();  // 获取年份
		  let month = newMonth.getMonth() + 1;  // 获取月份，并加 1
		
		  // 格式化月份，确保为两位数
		  month = month < 10 ? '0' + month : month;
		
		  // 拼接成 yyyy-MM 格式
		  const formattedMonth = `${year}-${month}`;
      this.getDaysInCurrentMonthDatas(formattedMonth);  // 获取选择月份的数据
    },

    // 格式化空值为0
    formatNullToZero(value) {
      return value !== undefined && value !== null ? value : 0;
    }
  }
};
</script>

<style scoped>
.scroll-hint {
  text-align: center;
  margin: 10px 0;
  font-size: 14px;
  color: #FF6347;
}

.example-body {
  text-align: center; /* 水平居中 */
}
</style>
