<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
		    <el-form-item label="检验月份" prop="yearMonthDate">
				<el-date-picker
				v-model="queryParams.yearMonthDate"
				type="month"
				placeholder="选择月">
				</el-date-picker>
			</el-form-item>

			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
				>导出</el-button>
				<span style="color:firebrick;font-size: small; text-align: center;padding-left:30px">说明：空白处表示当日未生产。</span>
			</el-form-item>
		</el-form>
		<el-tabs v-model="activeName" type="card">
			<el-tab-pane label="图表" name="first">
			    <el-form ref="form" :model="form" label-width="80px">
					<el-row>
						<el-col :span="24" style="text-align:center">
							<h2>{{titleYear}} 年 {{titleMonth}} 月 份 黑 蚊 香 成 品 包 装 不 良 排 列 图</h2>
						</el-col>
					</el-row>
				</el-form>
			<div id="echartss" style="width:1200px;height:450px;"></div>
			</el-tab-pane>
      <el-table v-loading="loading" :data="defectList" border height="500px" ref="tableRef">
        <el-table-column label="序号" type="index" align="center" :index="indexMethod"/>
        <el-table-column label="日期/不良项目" align="center" prop="dataType" min-width="100"/>
        <template v-for="(column, index) in showTitles">
          <el-table-column align="center" min-width="120" :prop="column.id" :key="column.id" :label="column.titleName"/>
        </template>
      </el-table>
<!--			<el-tab-pane label="报表" name="second">-->
<!--				<el-table v-loading="loading" :data="itemProList" border>-->
<!--					<el-table-column label="序号" type="index" align="center" :index="indexMethod" fixed/>-->
<!--					<el-table-column label="项目" align="center" prop="dataType" min-width="100" fixed>-->
<!--						<template v-for="(column, index) in showTitles">-->
<!--							<el-table-column align="center" min-width="120" :prop="column.id" :key="column.id" :label="column.titleName"/>-->
<!--						</template>-->
<!--					</el-table-column>-->
<!--				</el-table>-->
<!--			</el-tab-pane>-->
		</el-tabs>
	</div>
</template>

<script>
import { getCpDateTitle,getCpDefectDate} from "@/api/quality/qcTable";
import moment from 'moment';
import * as echarts from "echarts";
export default {
	name: "CpTranChart",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 备料单表格数据
			itemProList: [],
 			activeName: 'first',
      showTitles:[],//列表展示的小时段
      defectList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				yearMonthDate:null,
				pageNum: 1,
				pageSize: 10,
        checkType: 'checkTypeCPPC'
			},
			// 表单参数
			form: {},
      titleYear: null,
      titleMonth: null,
			spanArr: [],
      position: 0,
			content_style: {
				'text-align': 'center',
				'min-width': '200px',
				'word-break': 'break-all'
			},
			label_style: {
				'color': '#000',
				'text-align': 'center',
				'font-weight': '600',
				'height': '40px',
				'background-color': '#d6dbe1',
				'min-width': '100px',
				'word-break': 'keep-all'
			},
		};
	},
	created() {
    this.getDate();
		this.getList();
	},
	methods: {
        /**获取默认查询时间段**/
		getDate() {
			let start = this.Fungetdate (0);
			this.queryParams.yearMonthDate = start;
		},
		Fungetdate (num) {
			var dd = new Date();
			dd.setDate(dd.getDate() + num);
			var y = dd.getFullYear();
			var m = dd.getMonth() + 1;//获取当前月份的日期
			return y + "-" + m ;
		},

		/** 查询设备小时产量列表 */
    getList() {
      //this.titleYear = this.queryParams.yearMonthDate.split('-')[0];
     // this.titleMonth = this.queryParams.yearMonthDate.split('-')[1];
      console.log(moment(this.queryParams.yearMonthDate).format('YYYY-MM'));
      if(this.queryParams.yearMonthDate!=null){
        this.queryParams.yearMonth = moment(this.queryParams.yearMonthDate).format('YYYY-MM');
        this.titleYear = this.queryParams.yearMonth.split('-')[0];
        this.titleMonth = this.queryParams.yearMonth.split('-')[1];
      } else {
        this.$message.error("请填写月份");
        return;
      }

      this.loading = true;
      //获取Table表头
      getCpDateTitle(this.queryParams).then(response => {
        this.showTitles = [];
        for(let i=0;i<=response.length-1;i++){
          var pobj={};
          pobj.id="dataTitle"+i;
          pobj.titleName = response[i];
          this.showTitles.push(pobj)
        }
      });
      // 获取Table数据并在回调中初始化图表
      getCpDefectDate(this.queryParams).then(response => {
        this.defectList = response;
        this.loading = false;

        // 在数据获取完成后初始化图表
        this.initChart();
      });
    },

    initChart() {
      var chartDom = document.getElementById('echartss');
      if (!chartDom) {
        console.error('图表容器不存在');
        return;
      }

      var myChart = echarts.init(chartDom);

      // 从响应数据中提取X轴和Y轴数据
      const xAxisData = this.defectList.map(item => item.dataType);
      const yAxisData = this.defectList.map(item => parseFloat(item.dataTitle13.replace('%', '')));

      var option = {
        title: {
          text: '不良率数据趋势分析',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        legend: {
          right: '5%',    // 距离右侧5%
          top: '5%',      // 距离顶部5%
          orient: 'vertical'  // 可选：垂直排列图例
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `${params[0].name}<br/>${params[0].marker} 不良率: ${params[0].value}%`;
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLabel: {
            rotate: 45, // X轴标签旋转45度避免重叠
            interval: 0 // 显示所有标签
          }
        },
        yAxis: {
          type: 'value',
          min: 0.00,
          max: 10.00,
          axisLabel: {
            formatter: '{value}%'
          },
          name: '不良率',
          nameLocation: 'end'
        },
        series: [
          {
            name: '不良率',
            data: yAxisData,
            type: 'line',
            label: {
              show: true,
              position: 'top'
            },
          //  smooth: true, // 平滑曲线
            symbol: 'circle', // 数据点样式
            symbolSize: 8,
            lineStyle: {
              width: 3,
              color: '#5470c6'
            },
            itemStyle: {
              color: '#5470c6'
            },
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
                { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
              ])
            }
          }
        ]
      };

      // 使用配置项显示图表
      option && myChart.setOption(option);

      // 添加窗口大小变化时的自适应
      window.addEventListener('resize', function() {
        myChart.resize();
      });
    },
		// 表单重置
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},

		/** 导出按钮操作 */
		handleExport() {
			this.download('quality/staticTable/getDefectItemDataExport', {
				...this.queryParams
			}, `bpDefectItem_${new Date().getTime()}.xlsx`)
		},

	}
};
</script>
<style scoped>
.my-description-item1 {
  width: 200px; /* 或者你想要的任何宽度 */
}
</style>
