<template>
	<div class="app-container">
		<!-- 搜索部分 -->
		<div>
			<el-form :model="search" inline size="mini" label-width="80px">
				<el-form-item label="开始日期">
					<el-date-picker :style="{ width: inputWidth }" v-model="search.starttime" value-format="yyyy-MM-dd hh:mm:ss" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="结束日期">
					<el-date-picker :style="{ width: inputWidth }" v-model="search.endtime" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="批次号">
					<el-input v-model.trim="search.workorderid" placeholder="输入批次号" :style="{ width: inputWidth }"></el-input>
				</el-form-item>
				<el-form-item label="颜色代号">
					<el-input v-model.trim="search.partnumber" placeholder="颜色代号" :style="{ width: inputWidth }"></el-input>
				</el-form-item>
				<!-- <el-form-item label="产品描述">
					<el-input v-model.trim="search.product_description" placeholder="输入产品描述" :style="{ width: inputWidth }"></el-input>
				</el-form-item> -->
				<!-- <el-form-item label="班组">
					<el-select v-model="search.team" placeholder="输入班组" :style="{ width: inputWidth }">
						<el-option label="A班" value="A"> </el-option>
						<el-option label="B班" value="B"> </el-option>
						<el-option label="" value=""> </el-option>
					</el-select>
				</el-form-item> -->

				<!-- <el-form-item label="报表类型">
					<el-select v-model="search.reportType" placeholder="请选择" :style="{ width: inputWidth }">
						<el-option v-for="item in reportType_options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
					</el-select>
				</el-form-item> -->

				<BR></BR>
				<el-form-item label=" ">
					<el-button size="mini" type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
					<el-button size="mini" type="primary" @click="dialogVisible = true">增加记录</el-button>
					<!-- <el-button size="mini" type="primary" @click="dialogVisible = true">删除记录</el-button> -->
					<!-- <el-button size="mini" type="warning" @click="exportAllDataEvent(false)">日生产报表导出</el-button> --getList()>
					<el-button size="mini" type="success" @click="exportAllDataEvent(true)">导入数据</el-button>
					<el-button size="mini" type="success" @click="exportAllDataEvent(true)">导出数据</el-button>
					<el-button size="mini" type="success" @click="exportDataEvent">缺陷详情导出</el-button> -->

					<el-button size="mini" type="success" >导入数据</el-button>
					<el-button size="mini" type="success" @click="openExportEvent">导出数据</el-button>
					
				</el-form-item>
			</el-form>
		</div>
		<div style="width: 100%; display: flex; justify-content: flex-end">
			<pagination :pageSizes="[20, 30, 40, 50]" :total="pagination.total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize" @pagination="getList" />
		</div>
		<div style="width: 100%">
			<div style="font-size: 20px;text-align: center; margin 0 auto">
				{{ reportType_options[search.reportType].label }} 共 {{ realTotal }} 条
			</div>
		</div>
		<!-- 表格部分 -->
		<vxe-table @menu-click="contextMenuClickEvent" :menu-config="tableMenu" border  :header-cell-style="headerCellStyle" ref="xTable" 
						:column-config="{ resizable: true }" :row-config="{ isHover: false, isCurrent: false, height: 30 }" 
						:loading="loading" :data="QualityStatisticsTable" :merge-cells="mergeCells" 
						:cell-style="cellStyle" size="mini" align="center" max-height="800px" :export-config="{}"
						:edit-config="{trigger: 'click', mode: 'cell'}">
						
			<vxe-column field="code" title="颜色/代号" width="140px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.code" type="text"></vxe-input>
            	</template>
			</vxe-column>	
			<vxe-column field="pci" title="批次号" width="140px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.pci" type="text"></vxe-input>
            	</template>
			</vxe-column>						
			<vxe-column field="value01" title="角度" width="140px" ></vxe-column>

			<vxe-column field="value02" title="△L" min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.value02" type="text"   @blur.native.capture="updateUser(row.value02)"></vxe-input>
            	</template>
			</vxe-column>
			<vxe-column field="value03" title="△A" min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.value03" type="text"></vxe-input>
            	</template>
			</vxe-column>
			<vxe-column field="value04" title="△B" min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.value04" type="text"></vxe-input>
            	</template>
			</vxe-column>
			<vxe-column field="value05" title="△E"  min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.value05" type="text"></vxe-input>
            	</template>
			</vxe-column>		
			<vxe-column field="value06" title="mDE" min-width="100px" :edit-render="{autofocus: '.vxe-input--inner'}">
				<template #edit="{ row }">
              		<vxe-input v-model="row.value06" type="text"></vxe-input>
            	</template>
			</vxe-column>

			<vxe-colgroup title="膜厚" align="center">
				<vxe-column field="value07" title="名称" min-width="80px"></vxe-column>
				<vxe-column field="value08" title="数值" min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
					<template #edit="{ row }">
              			<vxe-input v-model="row.value08" type="text"></vxe-input>
            		</template>
				</vxe-column>
			</vxe-colgroup>

			<vxe-colgroup title="来料检" align="center">
				<vxe-column field="value09" title="粘度" min-width="60px" :edit-render="{autofocus: '.vxe-input--inner'}">
					<template #edit="{ row }">
              			<vxe-input v-model="row.value09" type="text"></vxe-input>
            		</template>	
				</vxe-column>
				<vxe-column field="value10" title="固含量" min-width="100px"  :edit-render="{autofocus: '.vxe-input--inner'}">
					<template #edit="{ row }">
						<vxe-input v-model="row.value10" type="text"></vxe-input>
					</template>
				</vxe-column>
				<vxe-column field="value11" title="电阻值" min-width="80px" :edit-render="{autofocus: '.vxe-input--inner'}">
					<template #edit="{ row }">
						<vxe-input v-model="row.value11" type="text"></vxe-input>
					</template>
				</vxe-column>
			</vxe-colgroup>

		</vxe-table>

		<el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
  			<span>确定增加一组数据</span>
  				<span slot="footer" class="dialog-footer">
    			<el-button @click="dialogVisible = false">取 消</el-button>
    			<el-button type="primary" @click="addData">确 定</el-button>
  			</span>
		</el-dialog>

	</div>
</template>

<script>
	import {
		downloadStatisticsTableExcel
	} from '@/api/qualityManagement/qualityStatistics_V2'

	import {
		GetRawMateriallist,
		AddRawMateriallist,
		UpdateRawMateriallist,
		DelRawMateriallist,
	} from '@/api/paintLabManagement/dataRawMaterial'

	export default {
		name: 'dataRawMaterial',
		data() {
			return {
				inputWidth: '180px',
				pickerOptions: {
					shortcuts: [
					{
						text: '今天',
						onClick(picker) {
							picker.$emit('pick', new Date())
						},
					},
					{
						text: '昨天',
						onClick(picker) {
							const date = new Date()
							date.setTime(date.getTime() - 3600 * 1000 * 24)
							picker.$emit('pick', date)
						},
					},
					{
						text: '一周前',
						onClick(picker) {
							const date = new Date()
							date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
							picker.$emit('pick', date)
						},
					}, ],
				},
				search: {
					starttime: new Date(new Date(new Date().toLocaleDateString()).getTime()),
					endtime: new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1),
					team: null,
					workorderid: null,
					partnumber: null,
					reportType: 0,
					product_description: '',
				},
				reportType_options: [
					{ label: '原材料记录', value: 0 },
				],
				pagination: {
					total: 0,
					pageNum: 1,
					pageSize: 30,
				},
				realTotal: 0,
				loading: false,
				QualityStatisticsTable: [],
				mergeCells: [
					// { row: 0, col: 0, rowspan: 3, colspan: 0 },
				],
				hiddenCells: [],
				// 列表对照表
				tableCellDict: [],
				// 右键菜单
				tableMenu: {
					header: {
						options: [
							[
								{ code: 'hideColumn', name: '隐藏列', disabled: false },
								{ code: 'showAllColumn', name: '取消所有隐藏列', disabled: false },
							],
						],
					},
					body: {
						options: [
							[
								// { code: 'copy', name: '复制', prefixIcon: 'vxe-icon-copy', disabled: false },
								// { code: 'reload', name: '刷新', disabled: false },
								// { code: 'insertAt', name: '插入', disabled: false },
								{ code: 'remove', name: '删除', disabled: false },
								// { code: 'save', name: '保存', prefixIcon: 'vxe-icon-save', disabled: false },
								{ code: 'update', name: '修改', disabled: false },
							],
						],
					},
					visibleMethod: this.visibleMethod,
				},
				// 后台数据结构
				serverData:[],
				dialogVisible: false,
			}
		},
		mounted() {
			this.getList()
		},
		created() {},
		methods: {
			//todo  设置表合并行
			mergeTable(num) {
				this.mergeCells = []
				for (let i = 0; i < this.QualityStatisticsTable.length; i = i + num) {
					let count = 13 - this.hiddenCells.length;

					// 颜色/代号   批次号
					this.mergeCells.push({ row: i, col: 0, rowspan: num, colspan: 0 });
					this.mergeCells.push({ row: i, col: 1, rowspan: num, colspan: 0 });

					// mDE
					this.mergeCells.push({ row: i, col: 7, rowspan: num, colspan: 0 });

					// 粘度  固含量  电阻值
					this.mergeCells.push({ row: i, col: 10, rowspan: num, colspan: 0 });
					this.mergeCells.push({ row: i, col: 11, rowspan: num, colspan: 0 });
					this.mergeCells.push({ row: i, col: 12, rowspan: num, colspan: 0 });
				}
			},

			updateUser(value){
				console.log(value)
			},

			//todo 添加数据行
			addData(){

				this.dialogVisible = false
				AddRawMateriallist({"num":1}).then((res) => {
						if (res.code == 200) {
							this.getList()
						}
					})
			},

			//todo 获取数据行
			getList() {
				this.loading = true
				setTimeout(() => {
					this.loading = false
				}, 30000)

				let query = { ...this.search, ...this.pagination }

				delete query['team']
				//query['workorderid']
				//delete query['partnumber']
				delete query['reportType']
				delete query['product_description']
				delete query['total']

				//console.log(query)

				GetRawMateriallist(query).then((res) => {
						if (res.code == 200) {
							
							this.QualityStatisticsTable = res.data.item1
							this.pagination.total = res.data.item2
							this.realTotal = this.pagination.total/5
							this.mergeTable(5)
							this.loading = false
							// console.log(res.data)
							// console.log(this.pagination.total)
						}
					})
			},

			//todo 设置表头颜色
			headerCellStyle() {
				return {
					backgroundColor: '#2D3D51',
					color: '#ffffff',
					border: '1px solid #161823',
					fontSize: '18px',
				}
			},

			cellStyle() {

				return {
					border: '1px solid #161823',
					fontSize: '16px',
					fontWeight: '700',
				}
			},

			//todo 导出excel
			exportDataEvent() {
				this.$refs.xTable.openExport()
			},
			// 导出全部数据
			exportAllDataEvent(isShowDetail = false) {
				let data = { ...this.search, ...this.pagination };
				data.type = this.search.reportType + 1;
				data.isShowDetail = isShowDetail;
				let fileName = this.reportType_options[this.search.reportType].label + (isShowDetail ? '-缺陷详情' : '-日生产报表') + '.xlsx';
				downloadStatisticsTableExcel(data).then(res => {
					console.log(res);
					let blobURL = URL.createObjectURL(res.data)
					//创建标签
					let link = document.createElement('a')
					//设置href
					link.href = blobURL
					//设置a标签的行为是download,不然就跳转了,同时设置名字是"test.ppt"
					link.download = fileName;
					//隐藏a标签，他只是下载，没必要出现
					link.style.display = "none"
					//模拟点击
					link.click()
					//最后，把这个URL进行销毁,免得他占内存
					URL.revokeObjectURL()
				})
				// this.download('/mes/qc/statistics/downloadStatisticsTableExcel');
			},

			// 合格率去除小数
			offsetRate(num) {
				if (num === null) {
					return ''
				}
				return parseInt(num)
			},

			// 数据去除0
			offsetValue(num) {
				if (num === 0 || num === '0') {
					return ''
				}
				return num
			},

			// 右键菜单
			contextMenuClickEvent({ menu, row, column }) {
				const $table = this.$refs.xTable
				switch (menu.code) {
				case 'hideColumn':
					this.hideColumn(column);
					break
				case 'showAllColumn':
					this.resetColumn()
					break
				case 'remove':
					this.removeData(row)
					// $table.remove(row)
					break
				case 'update':
					this.updateData(row)
					break
				}
			},

			// 隐藏列
			hideColumn(column) {
				const $table = this.$refs.xTable;
				$table.hideColumn(column);
				this.hiddenCells.push(column.title);
				this.resetMergeTable();
			},

			// 取消所有隐藏列
			resetColumn() {
				const $table = this.$refs.xTable;
				this.hiddenCells = [];
				$table.resetColumn();
				this.resetMergeTable();
			},

			resetMergeTable(){
				if(this.search.reportType  === 3){
					this.mergeTable(2);
				}else{
					this.mergeTable(3);
				}
				
			},

			// 删除数据
			removeData(row) {
				this.$confirm('此操作将永久删除改组记录, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					const deleteData = {
						idGroup: row.idGroup,
					}
					DelRawMateriallist(deleteData).then((res) => {
						if (res.code === 200) {
							this.$message({
								type: 'success',
								message: '删除成功!',
							})
							this.getList()
						} else {
							this.$message({
								type: 'error',
								message: '删除失败!请检查!',
							})
						}
					})
				})
			},

			//修改数据
			updateData(row) {
				// 查找行号
				var index = 0;
				for (const number of this.QualityStatisticsTable) {  
  					if (row.id === number.id) {  
    					break; // 成功中断循环  
  					}
					else index = index + 1;
				}
				//onsole.log(index);

				// 计算每组数据的，第一行
				const baseValue = parseInt((index)/5) * 5;
				const updateData1 = {
					id:1,
					plIdGroup:"",
					plCode:"",
					plPci:"",
					plValue01:"",
					plValue02:"",
					plValue03:"",
					plValue04:"",
					plValue05:"",
					plValue06:"",
					plValue07:"",
					plValue08:"",
					plValue09:"",
					plValue10:"",
					plValue11:"",
					plCreatedBy:"",
					plCreatedTime:"",
					plUpdatedBy:"",
					plUpdatedTime:"",
					};

				// 获取表格数据
				this.serverData = [];
				this.serverData.push(updateData1);
				this.serverData.push({ ...updateData1 });
				this.serverData.push({ ...updateData1 });
				this.serverData.push({ ...updateData1 });
				this.serverData.push({ ...updateData1 });
				//console.log(this.QualityStatisticsTable[baseValue])
				for(var i=0;i<5;i++){
					this.serverData[i].id = this.QualityStatisticsTable[baseValue+i].id;
					this.serverData[i].plIdGroup = this.QualityStatisticsTable[baseValue+i].idGroup;
					this.serverData[i].plCode = this.QualityStatisticsTable[baseValue].code;	// 有合并
					this.serverData[i].plPci = this.QualityStatisticsTable[baseValue].pci;	// 有合并
					this.serverData[i].plValue01 = this.QualityStatisticsTable[baseValue+i].value01;
					this.serverData[i].plValue02 = this.QualityStatisticsTable[baseValue+i].value02;
					this.serverData[i].plValue03 = this.QualityStatisticsTable[baseValue+i].value03;
					this.serverData[i].plValue04 = this.QualityStatisticsTable[baseValue+i].value04;
					this.serverData[i].plValue05 = this.QualityStatisticsTable[baseValue+i].value05;
					this.serverData[i].plValue06 = this.QualityStatisticsTable[baseValue].value06;// 有合并
					this.serverData[i].plValue07 = this.QualityStatisticsTable[baseValue+i].value07;
					this.serverData[i].plValue08 = this.QualityStatisticsTable[baseValue+i].value08;
					this.serverData[i].plValue09 = this.QualityStatisticsTable[baseValue].value09;// 有合并
					this.serverData[i].plValue10 = this.QualityStatisticsTable[baseValue].value10;// 有合并
					this.serverData[i].plValue11 = this.QualityStatisticsTable[baseValue].value11;// 有合并
					this.serverData[i].plCreatedBy = this.QualityStatisticsTable[baseValue+i].createdBy;
					this.serverData[i].plCreatedTime = this.QualityStatisticsTable[baseValue+i].createdTime;
					this.serverData[i].plUpdatedBy = this.QualityStatisticsTable[baseValue+i].updatedBy;
					this.serverData[i].plUpdatedTime = this.QualityStatisticsTable[baseValue+i].updatedTime;
				}
				
				// 数据传输到后台
				UpdateRawMateriallist(this.serverData).then((res) => {
					if (res.code == 200) {
						//console.log(res.data)
						this.$message({
          					showClose: true,
          					message: '更新成功-' + res.data,
          					type: 'success'
        				});
					}
				})
			},
			// 导出
			openExportEvent () {
				 this.$refs.xTable.openExport();
			}

		},
	}
</script>

<style lang="scss" scoped></style>