<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 label="白坯名称" prop="materialName">
				<el-input
					v-model="queryParams.materialName"
					placeholder="请输入白坯名称"
					clearable
					@keyup.enter.native="handleQuery"
				/>
			</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" @tab-click="handleClick">
			<el-tab-pane label="报表" name="first">
				<el-table v-loading="loading" :data="hourProList" :span-method="objectSpanMethod" border>
					<el-table-column label="序号" type="index" align="center" :index="indexMethod" fixed/>
					<el-table-column label="白坯名称" align="center" prop="materialName" min-width="100" 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>
			</el-tab-pane>	
			<el-tab-pane label="图表" name="second">
				<div id="echartss" style="width:1200px;height:450px;"></div>
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script>
import {getMonthOfDateTitle, getMonthOfData,getMonthOfLine} from "@/api/quality/qcTable";
import moment from 'moment';
import * as echarts from "echarts";
export default {
	name: "BpNookRate",
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 备料单表格数据
			hourProList: [],
 			activeName: 'first',
            showTitles:[],//列表展示的小时段

			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				yearMonthDate:null,
				yearMonth:null,
				productDateArray: [],
				pageNum: 1,
				pageSize: 10,
				workorderCode: null,
				workorderName: null,
				parentOrder: null,
				orderId: null,
				orderCode: null,
				productId: null,
				productCode: null,
				prodType: null,
				productName: null,
				productSpc: null,
				productDate: null,
				equTypeCode: "equ_type_hf"
			},
			// 表单参数
			form: {},
			// 班次list
            workShift: [],
			equipmentTypeOption:[
				{equipmentTypeCode:"equ_type_cxj",equipmentTypeName:"成型机"},
				{equipmentTypeCode:"equ_type_hf",equipmentTypeName:"烘房"}
			],
			spanArr: [],
            position: 0
		};
	},
	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() {

			if(this.queryParams.yearMonthDate!=null){
				this.queryParams.yearMonth = moment(this.queryParams.yearMonthDate).format('YYYY-MM');
			}else{
				this.$message.error("请填写月份");
				return
			}

			this.spanArr = [];
			this.position = 0;

			this.loading = true;
            //获取Table表头
			getMonthOfDateTitle(this.queryParams).then(response => {
				this.showTitles = [];
				for(let i=0;i<=response.length-1;i++){
					var pobj={};
					pobj.id="monthNum"+i;
					pobj.titleName = response[i];
					this.showTitles.push(pobj)
				}
			});
            //获取Table数据
			getMonthOfData(this.queryParams).then(response => {
				this.hourProList = response;
				this.rowspan();
				
				this.loading = false;
			});
            //获取图表数据
			this.getTbody();
		},

		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				prepareId: null,
				workorderCode: null,
				workorderName: null,
				parentOrder: null,
				orderId: null,
				orderCode: null,
				productId: null,
				productCode: null,
				prodType: null,
				productName: null,
				productSpc: null,
				wetDetailPlanId: null,
				productDate: null,
				shiftId: null,
				ancestors: null,
				status: null,
				remark: null,
				attr1: null,
				attr2: null,
				attr3: null,
				attr4: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				factoryCode: null
			};
			this.resetForm("form");
			this.spanArr = [];
			this.position = 0;
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},

		/** 导出按钮操作 */
		handleExport() {
			this.download('mes/reportWork/getHourProductionNewExport', {
				...this.queryParams
			}, `hourProduction_${new Date().getTime()}.xlsx`)
		},


		handleClick(){
			this.$nextTick(()=>{
				this.$refs.tables.doLayout()//对table进行重新布局
			})
		},
		async getTbody(){
			this.loading=true
			this.$nextTick(()=>{
				this.$refs.tables.doLayout()//对table进行重新布局
			})
            let _this = this
			let xData=[]
			let yData=[]
			getMonthOfLine(this.queryParams).then(response => {
				response.map((item,index)=>{
					xData.push(item.ymdms),
					yData.push(item.noOkBatchRate)				
				})
				_this.getEcharts(xData,yData)
			});
			
		},
		getEcharts(xData,yData){
			var _this=this
			var chartDom = document.getElementById('echartss');
			var myChart = echarts.init(chartDom);
			var option;
			option = {
				grid: {
					y: '5%',
					x:'1%',
					y2: '6%',
					x2: '1%',
					width:'96%',
					containLabel: true
				},
				xAxis: {
					type: 'category',
					name: '日',
					splitLine: {
						show: true  //分隔线，默认数值轴显示，类目轴不显示
					},
					axisTick:{
						show:false,
						inside:true,
					},
					axisLabel:{
						rotate: 50,
						fontSize:11
					},
					
					data: xData
				},
				yAxis: {
					type: 'value',
					show:true,
					// boundaryGap:true,
					axisLine:{
						// show:true,
					},
					axisLabel:{
						formatter:'{value}%'
					}
				},
				series: [
					{   
						name:'不良率%',
						data: yData,
						type: 'line',
						symbol: "circle",
						symbolSize: 5,
						label:{
							show:true,
							fontSize:11
						},
						lineStyle: {
							color: "rgba(12, 115, 242, 1)"
						},
						areaStyle:{
							normal: {
								color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [{
									offset: 0,
									color: "#fff" // 0% 处的颜色
								}, {
									offset: 1,
									color: "rgba(12, 115, 242, 1)" // 100% 处的颜色
								}], false)
							},
						}
					}
				]
				};

				option && myChart.setOption(option);	
		},

		// 生成表头序号
		indexMethod(index) {
			return index + 1;
		},
		/**
		* 1. 若是objectSpanMethod不返回任何东西，表格不会变化
		* 2. 最外层的判断一般是，先从第几列开始合并
		* 3. 这次从第0行合并2个，下次就要从第3行开始合并（0行加俩，就到3行了）
		* 4. 这种方式是有多少条数据，合并多少条数据，比如本案例中有7条数据（从第0条合并到第7条）
		* 5. return { rowspan: 0, colspan: 0 } // 表示不合并
		* */
		rowspan() {
          this.hourProList.forEach((item, index) => {
            if (index === 0) {
			  this.spanArr.push(1);
              this.position = 0;
            } else {
               if (
              this.hourProList[index].materialName ===
              this.hourProList[index - 1].materialName
              ) {
              this.spanArr[this.position] += 1;
              this.spanArr.push(0);
            } else {
              this.spanArr.push(1);
              this.position = index;
             }
           }
         });
       },
       objectSpanMethod({ row, column, rowIndex, columnIndex }) {
			if (columnIndex === 1) {
			const _row = this.spanArr[rowIndex];
			const _col = _row > 0 ? 1 : 0;
			return {
				rowspan: _row,
				colspan: _col,
			};
			}
       },
	}
};
</script>
