<template>
	<el-container>
		<el-header>
			<div class="right-panel">
				<el-select v-model="queryType" @change="queryTypeChange">
					<el-option v-for="item in typeOptions" 
					:key="item" 
					:label="item" 
					:value="item"
					>
					</el-option>
				</el-select>
				<el-date-picker
					v-if="queryType=='月'"
					v-model="queryDate"
					type="month"
					placeholder="查询月期"
					value-format="YYYY-MM"
					style="width:100%"
				>
				</el-date-picker>
				<el-date-picker
					v-if="queryType=='年'"
					v-model="queryDate"
					type="year"
					placeholder="查询年份"
					value-format="YYYY"
					style="width:100%"
				>
				</el-date-picker>
				<el-button type="primary" icon="el-icon-search" @click="handleQuery"></el-button>
			</div>
		</el-header>
		<el-main>
			<el-card shadow="never" style="margin-bottom: 8px;">
				<el-header>
					<div class="right-panel">
						<h2>各工段检验</h2>
						<el-select v-model="mgroup" clearable @change="mgroupChange">
							<el-option v-for="item in mgroupOption" 
							:key="item.id" 
							:label="item.name" 
							:value="item.id"
							>
							</el-option>
						</el-select>
					</div>
				</el-header>
				<el-row :gutter="15">
					<el-col :lg="8">
						<scEcharts height="500px" :option="option1"></scEcharts>
					</el-col>
					<el-col :lg="16" style="position: relative;">
						<el-button @click="handleExport('1')" class="tables" type="primary">导出</el-button>
						<el-table :data="tableData" :height="500" id="exportDiv1" :summary-method="getSummaries" show-summary>
							<el-table-column type="index" width="50" />
							<el-table-column label="日期" prop="date" 
							:filters="dateFilters"
							:filter-method="filterDate"
							filter-placement="bottom-end">
								<template #default="scope">
									<span>{{ scope.row.年 }}</span>
									<span v-if="scope.row.月">-{{ scope.row.月 }}</span>
								</template>
							</el-table-column>
							<el-table-column label="规格" prop="规格" 
							 	:filters="specsFilters"
								:filter-method="filterSpecs"
								filter-placement="bottom-end">
							</el-table-column>
							<el-table-column label="型号" prop="型号" 
								:filters="modelFilters"
								:filter-method="filterModel"
								filter-placement="bottom-end">
							</el-table-column>
							<el-table-column label="合格数" prop="合格数">
							</el-table-column>
							<el-table-column label="不合格数" prop="合格数">
								<el-table-column label="条纹" prop="条纹"></el-table-column>
								<el-table-column label="气泡" prop="气泡"></el-table-column>
								<el-table-column label="断裂" prop="断裂"></el-table-column>
								<el-table-column label="气线" prop="气线"></el-table-column>
								<el-table-column label="炸纹" prop="炸纹"></el-table-column>
								<el-table-column label="结石" prop="结石"></el-table-column>
								<el-table-column label="弯曲" prop="弯曲"></el-table-column>
								<el-table-column label="偏壁" prop="偏壁"></el-table-column>
								<el-table-column label="大小头" prop="大小头"></el-table-column>
								<el-table-column label="其他" prop="其他"></el-table-column>
								<el-table-column label="合计" prop="不合格数"></el-table-column>
							</el-table-column>
						</el-table>
					</el-col>
				</el-row>
			</el-card>
		</el-main>
	</el-container>
</template>
<script>
	import scEcharts from '@/components/scEcharts';
	export default {
		name: 'chart',
		components: {
			scEcharts
		},
		data() {
			return {
				queryType:'月',
				queryDate:'',
				start_date:'',
				end_date:'',
				currentYear:'',
				currentMonth:'',
				typeOptions:['月','年'],
				option1: {
					tooltip: {
						trigger: 'item'
					},
					series: [
						{
							name: '工序检验',
							type: 'pie',
							radius: ['40%', '60%'],
							center: ['50%', '60%'],
							label: {
								show: true,
								formatter: '{b} : {c}',
							},
							data: [
								{value: 1048, name: '合格数'},
								{value: 735, name: '不合格一'},
								{value: 580, name: '不合格二'},
								{value: 484, name: '不合格三'}
							]
						}
					]
				},
				mgroup:'',
				mgroupName:'',
				mgroupOption:[],
				tableData:[],
				dateFilters:[],
				specsFilters:[],
				modelFilters:[],
			}
		},
		mounted(){
			let date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth()+1;
			let days = new Date(year, month, 0).getDate();
			month = month<10?'0'+month:month;
			console.log(year,month,days)
			this.currentYear = year;
			this.currentMonth = month;
			this.queryDate = year + '-' + month;
			this.start_date =year+'-'+month+'-01';
			this.end_date = year+'-'+month+'-'+new Date(year, month, 0).getDate();
			this.getMgroup();
		},
		methods:{
			queryTypeChange(value){
				console.log(value)
				this.queryDate = '';
			},
			getMgroup(){
				this.$API.mtm.mgroup.list.req({belong_dept__name:'6车间',page:0}).then((res) => {
					this.mgroupOption = res;
					this.mgroup = res[0].id;
					this.mgroupName = res[0].name;
					this.getData();
				});
			},
			mgroupChange() {
				this.mgroupName = this.mgroupOption.find(item => item.id === this.mgroup).name;
				this.getData();
			},
			getData(){
				let that = this;
				that.dateFilters = [];
				that.modelFilters = [];
				that.specsFilters = [];
				let dateList=[],specsList=[],modelList=[];
				let exec = that.queryType=='月'?'lineMonth':'lineYear';
				let obj = {
					query: {
						end_date: that.end_date,
						start_date: that.start_date,
						mgroup_name: that.mgroupName,group_bys_mgroup: ", mgroup.name",
						group_bys_material: "",order_bys_material: "",
						select_cols_mgroup: ", mgroup.name AS 工段",
						select_cols_material: "",
						is_count_utask: -1
					},
				};
				//获取echarts数据
				that.$API.bi.dataset.exec.req(exec, obj).then((res) => {
					if (res.data2.ds0) { 
						let data = res.data2.ds0;
						let seriesData = [
							{value: 0, name: '合格数'},
							{value: 0, name: '条纹'},
							{value: 0, name: '气泡'},
							{value: 0, name: '断裂' },
							{value: 0, name: '气线' },
							{value: 0, name: '炸纹'},
							{value: 0, name: '结石'},
							{value: 0, name: '弯曲' },
							{value: 0, name: '偏壁'},
							{value: 0, name: '大小头'},
							{value: 0, name: '其他'},
						];
						if (data.length > 0) { 
							data.forEach((item) => {
								let other_count = item.不合格数 - item.条纹 - item.气泡 - item.断裂 - item.气线 - item.炸纹 - item.结石 - item.弯曲 - item.偏壁 - item.大小头;
								seriesData[0].value += item.合格数;
								seriesData[1].value += item.条纹;
								seriesData[2].value += item.气泡;
								seriesData[3].value += item.断裂;
								seriesData[4].value += item.气线;
								seriesData[5].value += item.炸纹;
								seriesData[6].value += item.结石;
								seriesData[7].value += item.弯曲;
								seriesData[8].value += item.偏壁;
								seriesData[9].value += item.大小头;
								seriesData[10].value += other_count;
							    // seriesData.forEach((item2) => {
							    //     item2.value += item[item2.name];
							    // })
							})
						}
						that.option1.series[0].data = seriesData;
					}
				});
				let obj2 = {
					query: {
						start_date: that.start_date, end_date: that.end_date,
						mgroup_name: that.mgroupName,group_bys_mgroup: ", mgroup.name",
  						select_cols_mgroup: ", mgroup.name AS 工段",
						is_count_utask: -1
					},
				};
				//获取table数据
				that.$API.bi.dataset.exec.req(exec, obj2).then((res2) => {
					let data = res2.data2.ds0;
					data.forEach((item) => {
					    let other_count = item.不合格数 - item.条纹 - item.气泡 - item.断裂 - item.气线 - item.炸纹 - item.结石 - item.弯曲 - item.偏壁 - item.大小头;
						item.其他 = other_count;
					})
					that.tableData = res2.data2.ds0;
					data.forEach((item) => {
						let date =item.年;
						if(that.queryType=='月'){
							date =item.年+'-'+item.月;
						}
					    if(dateList.indexOf(date)>-1){}else{
							dateList.push(date);
							let obj = {};
                            obj.text = date;
                            obj.value = date;
                            that.dateFilters.push(obj);
						}
						if(modelList.indexOf(item.型号)>-1){}else{
                            modelList.push(item.型号);
                            let obj2 = {};
                            obj2.text = item.型号;
                            obj2.value = item.型号;
                            that.modelFilters.push(obj2);
                        }
                        if(specsList.indexOf(item.规格)>-1){}else{
                            specsList.push(item.规格);
                            let obj3 = {};
                            obj3.text = item.规格;
                            obj3.value = item.规格;
                            that.specsFilters.push(obj3);
                        }
					})
				});
			},
			handleQuery(){
				if(this.queryDate!==''){
					if(this.queryType=='月'){
						this.start_date =this.queryDate+'-01';
						let arr = this.queryDate.split('-');
						this.end_date = this.queryDate+'-'+new Date(arr[0], arr[1], 0).getDate();
					}else{
						this.start_date = this.queryDate+'-01-01';
						this.end_date = this.queryDate+'-12-31';
					}
				}else{
					if(this.queryType=='月'){
						this.start_date =this.currentYear+'-'+this.currentMonth+'-01';
						this.end_date = this.currentYear+'-'+this.currentMonth+'-'+new Date(this.currentYear, this.currentMonth, 0).getDate();
					}else{
						this.start_date = this.currentYear+'-01-01';
						this.end_date = this.currentYear+'-12-31';
					}
				}
				this.getData();
			},
			getSummaries({ columns, data }) {
				const sums = [];
				columns.forEach((column, index) => {
					if (index === 0) {
						sums[index] = "合计";
						return;
					}
					if (index == 4) {
						const values = data.map((item) =>
							Number(item[column.property])
						);
						if (!values.every((value) => Number.isNaN(value))) {
							sums[index] = values.reduce((prev, curr) => {
								const value = Number(curr); //Number转换为数值
								let sum = Number(
									Number(prev) + Number(curr)
								).toFixed(2); //toFixed(2)数据项保留两位小数
								if (!isNaN(value)) {
									return sum;
								} else {
									return prev;
								}
							}, 0);
						} 
					}
				});
				return sums;
			},
			filterDate(value, row) {
				let date = row.年;
				if(this.queryType=='月'){
					date =row.年+'-'+row.月;
				}
				return date === value;
			},
			filterSpecs(value, row) {
				return row.规格 === value;
			},
			filterModel(value, row) {
				return row.型号 === value;
			},
			handleExport(val) {
				this.exportLoading = true;
				let id = '#exportDiv' + val;
				let name = val == '1' ? '各工序检验统计' : '成品检验统计';
				this.$XLSX(id, name);
				this.exportLoading = false;
			},
		},
	}
</script>

<style scoped>
.tables {
    position: absolute;
    top: 4px;
    right: 6px;
    z-index: 10;
}
</style>
